home *** CD-ROM | disk | FTP | other *** search
/ Nautilus 1992 July / Nautilus-3-8 / Nautilus-3-8.bin / Tools & Utilities / Techy Stuff / Development Environments ƒ / Perl 4.0.2 ƒ / unix / perl.man < prev    next >
Encoding:
Text File  |  1992-01-05  |  185.5 KB  |  5,925 lines

  1. .rn '' }`
  2. ''' $RCSfile: perl.man,v $$Revision: 4.0.1.5 $$Date: 91/11/11 16:42:00 $
  3. ''' 
  4. ''' $Log:    perl.man,v $
  5. ''' Revision 4.0.1.5  91/11/11  16:42:00  lwall
  6. ''' patch19: added little-endian pack/unpack options
  7. ''' 
  8. ''' Revision 4.0.1.4  91/11/05  18:11:05  lwall
  9. ''' patch11: added sort {} LIST
  10. ''' patch11: added eval {}
  11. ''' patch11: documented meaning of scalar(%foo)
  12. ''' patch11: sprintf() now supports any length of s field
  13. ''' 
  14. ''' Revision 4.0.1.3  91/06/10  01:26:02  lwall
  15. ''' patch10: documented some newer features in addenda
  16. ''' 
  17. ''' Revision 4.0.1.2  91/06/07  11:41:23  lwall
  18. ''' patch4: added global modifier for pattern matches
  19. ''' patch4: default top-of-form format is now FILEHANDLE_TOP
  20. ''' patch4: added $^P variable to control calling of perldb routines
  21. ''' patch4: added $^F variable to specify maximum system fd, default 2
  22. ''' patch4: changed old $^P to $^X
  23. ''' 
  24. ''' Revision 4.0.1.1  91/04/11  17:50:44  lwall
  25. ''' patch1: fixed some typos
  26. ''' 
  27. ''' Revision 4.0  91/03/20  01:38:08  lwall
  28. ''' 4.0 baseline.
  29. ''' 
  30. ''' 
  31. .de Sh
  32. .br
  33. .ne 5
  34. .PP
  35. \fB\\$1\fR
  36. .PP
  37. ..
  38. .de Sp
  39. .if t .sp .5v
  40. .if n .sp
  41. ..
  42. .de Ip
  43. .br
  44. .ie \\n(.$>=3 .ne \\$3
  45. .el .ne 3
  46. .IP "\\$1" \\$2
  47. ..
  48. '''
  49. '''     Set up \*(-- to give an unbreakable dash;
  50. '''     string Tr holds user defined translation string.
  51. '''     Bell System Logo is used as a dummy character.
  52. '''
  53. .tr \(*W-|\(bv\*(Tr
  54. .ie n \{\
  55. .ds -- \(*W-
  56. .if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
  57. .if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
  58. .ds L" ""
  59. .ds R" ""
  60. .ds L' '
  61. .ds R' '
  62. 'br\}
  63. .el\{\
  64. .ds -- \(em\|
  65. .tr \*(Tr
  66. .ds L" ``
  67. .ds R" ''
  68. .ds L' `
  69. .ds R' '
  70. 'br\}
  71. .TH PERL 1 "\*(RP"
  72. .UC
  73. .SH NAME
  74. perl \- Practical Extraction and Report Language
  75. .SH SYNOPSIS
  76. .B perl
  77. [options] filename args
  78. .SH DESCRIPTION
  79. .I Perl
  80. is an interpreted language optimized for scanning arbitrary text files,
  81. extracting information from those text files, and printing reports based
  82. on that information.
  83. It's also a good language for many system management tasks.
  84. The language is intended to be practical (easy to use, efficient, complete)
  85. rather than beautiful (tiny, elegant, minimal).
  86. It combines (in the author's opinion, anyway) some of the best features of C,
  87. \fIsed\fR, \fIawk\fR, and \fIsh\fR,
  88. so people familiar with those languages should have little difficulty with it.
  89. (Language historians will also note some vestiges of \fIcsh\fR, Pascal, and
  90. even BASIC-PLUS.)
  91. Expression syntax corresponds quite closely to C expression syntax.
  92. Unlike most Unix utilities,
  93. .I perl
  94. does not arbitrarily limit the size of your data\*(--if you've got
  95. the memory,
  96. .I perl
  97. can slurp in your whole file as a single string.
  98. Recursion is of unlimited depth.
  99. And the hash tables used by associative arrays grow as necessary to prevent
  100. degraded performance.
  101. .I Perl
  102. uses sophisticated pattern matching techniques to scan large amounts of
  103. data very quickly.
  104. Although optimized for scanning text,
  105. .I perl
  106. can also deal with binary data, and can make dbm files look like associative
  107. arrays (where dbm is available).
  108. Setuid
  109. .I perl
  110. scripts are safer than C programs
  111. through a dataflow tracing mechanism which prevents many stupid security holes.
  112. If you have a problem that would ordinarily use \fIsed\fR
  113. or \fIawk\fR or \fIsh\fR, but it
  114. exceeds their capabilities or must run a little faster,
  115. and you don't want to write the silly thing in C, then
  116. .I perl
  117. may be for you.
  118. There are also translators to turn your
  119. .I sed
  120. and
  121. .I awk
  122. scripts into
  123. .I perl
  124. scripts.
  125. OK, enough hype.
  126. .PP
  127. Upon startup,
  128. .I perl
  129. looks for your script in one of the following places:
  130. .Ip 1. 4 2
  131. Specified line by line via
  132. .B \-e
  133. switches on the command line.
  134. .Ip 2. 4 2
  135. Contained in the file specified by the first filename on the command line.
  136. (Note that systems supporting the #! notation invoke interpreters this way.)
  137. .Ip 3. 4 2
  138. Passed in implicitly via standard input.
  139. This only works if there are no filename arguments\*(--to pass
  140. arguments to a
  141. .I stdin
  142. script you must explicitly specify a \- for the script name.
  143. .PP
  144. After locating your script,
  145. .I perl
  146. compiles it to an internal form.
  147. If the script is syntactically correct, it is executed.
  148. .Sh "Options"
  149. Note: on first reading this section may not make much sense to you.  It's here
  150. at the front for easy reference.
  151. .PP
  152. A single-character option may be combined with the following option, if any.
  153. This is particularly useful when invoking a script using the #! construct which
  154. only allows one argument.  Example:
  155. .nf
  156.  
  157. .ne 2
  158.     #!/usr/bin/perl \-spi.bak    # same as \-s \-p \-i.bak
  159.     .\|.\|.
  160.  
  161. .fi
  162. Options include:
  163. .TP 5
  164. .BI \-0 digits
  165. specifies the record separator ($/) as an octal number.
  166. If there are no digits, the null character is the separator.
  167. Other switches may precede or follow the digits.
  168. For example, if you have a version of
  169. .I find
  170. which can print filenames terminated by the null character, you can say this:
  171. .nf
  172.  
  173.     find . \-name '*.bak' \-print0 | perl \-n0e unlink
  174.  
  175. .fi
  176. The special value 00 will cause Perl to slurp files in paragraph mode.
  177. The value 0777 will cause Perl to slurp files whole since there is no
  178. legal character with that value.
  179. .TP 5
  180. .B \-a
  181. turns on autosplit mode when used with a
  182. .B \-n
  183. or
  184. .BR \-p .
  185. An implicit split command to the @F array
  186. is done as the first thing inside the implicit while loop produced by
  187. the
  188. .B \-n
  189. or
  190. .BR \-p .
  191. .nf
  192.  
  193.     perl \-ane \'print pop(@F), "\en";\'
  194.  
  195. is equivalent to
  196.  
  197.     while (<>) {
  198.         @F = split(\' \');
  199.         print pop(@F), "\en";
  200.     }
  201.  
  202. .fi
  203. .TP 5
  204. .B \-c
  205. causes
  206. .I perl
  207. to check the syntax of the script and then exit without executing it.
  208. .TP 5
  209. .BI \-d
  210. runs the script under the perl debugger.
  211. See the section on Debugging.
  212. .TP 5
  213. .BI \-D number
  214. sets debugging flags.
  215. To watch how it executes your script, use
  216. .BR \-D14 .
  217. (This only works if debugging is compiled into your
  218. .IR perl .)
  219. Another nice value is \-D1024, which lists your compiled syntax tree.
  220. And \-D512 displays compiled regular expressions.
  221. .TP 5
  222. .BI \-e " commandline"
  223. may be used to enter one line of script.
  224. Multiple
  225. .B \-e
  226. commands may be given to build up a multi-line script.
  227. If
  228. .B \-e
  229. is given,
  230. .I perl
  231. will not look for a script filename in the argument list.
  232. .TP 5
  233. .BI \-i extension
  234. specifies that files processed by the <> construct are to be edited
  235. in-place.
  236. It does this by renaming the input file, opening the output file by the
  237. same name, and selecting that output file as the default for print statements.
  238. The extension, if supplied, is added to the name of the
  239. old file to make a backup copy.
  240. If no extension is supplied, no backup is made.
  241. Saying \*(L"perl \-p \-i.bak \-e "s/foo/bar/;" .\|.\|. \*(R" is the same as using
  242. the script:
  243. .nf
  244.  
  245. .ne 2
  246.     #!/usr/bin/perl \-pi.bak
  247.     s/foo/bar/;
  248.  
  249. which is equivalent to
  250.  
  251. .ne 14
  252.     #!/usr/bin/perl
  253.     while (<>) {
  254.         if ($ARGV ne $oldargv) {
  255.             rename($ARGV, $ARGV . \'.bak\');
  256.             open(ARGVOUT, ">$ARGV");
  257.             select(ARGVOUT);
  258.             $oldargv = $ARGV;
  259.         }
  260.         s/foo/bar/;
  261.     }
  262.     continue {
  263.         print;    # this prints to original filename
  264.     }
  265.     select(STDOUT);
  266.  
  267. .fi
  268. except that the
  269. .B \-i
  270. form doesn't need to compare $ARGV to $oldargv to know when
  271. the filename has changed.
  272. It does, however, use ARGVOUT for the selected filehandle.
  273. Note that
  274. .I STDOUT
  275. is restored as the default output filehandle after the loop.
  276. .Sp
  277. You can use eof to locate the end of each input file, in case you want
  278. to append to each file, or reset line numbering (see example under eof).
  279. .TP 5
  280. .BI \-I directory
  281. may be used in conjunction with
  282. .B \-P
  283. to tell the C preprocessor where to look for include files.
  284. By default /usr/include and /usr/lib/perl are searched.
  285. .TP 5
  286. .BI \-l octnum
  287. enables automatic line-ending processing.  It has two effects:
  288. first, it automatically chops the line terminator when used with
  289. .B \-n
  290. or
  291. .B \-p ,
  292. and second, it assigns $\e to have the value of
  293. .I octnum
  294. so that any print statements will have that line terminator added back on.  If
  295. .I octnum
  296. is omitted, sets $\e to the current value of $/.
  297. For instance, to trim lines to 80 columns:
  298. .nf
  299.  
  300.     perl -lpe \'substr($_, 80) = ""\'
  301.  
  302. .fi
  303. Note that the assignment $\e = $/ is done when the switch is processed,
  304. so the input record separator can be different than the output record
  305. separator if the
  306. .B \-l
  307. switch is followed by a
  308. .B \-0
  309. switch:
  310. .nf
  311.  
  312.     gnufind / -print0 | perl -ln0e 'print "found $_" if -p'
  313.  
  314. .fi
  315. This sets $\e to newline and then sets $/ to the null character.
  316. .TP 5
  317. .B \-n
  318. causes
  319. .I perl
  320. to assume the following loop around your script, which makes it iterate
  321. over filename arguments somewhat like \*(L"sed \-n\*(R" or \fIawk\fR:
  322. .nf
  323.  
  324. .ne 3
  325.     while (<>) {
  326.         .\|.\|.        # your script goes here
  327.     }
  328.  
  329. .fi
  330. Note that the lines are not printed by default.
  331. See
  332. .B \-p
  333. to have lines printed.
  334. Here is an efficient way to delete all files older than a week:
  335. .nf
  336.  
  337.     find . \-mtime +7 \-print | perl \-nle \'unlink;\'
  338.  
  339. .fi
  340. This is faster than using the \-exec switch of find because you don't have to
  341. start a process on every filename found.
  342. .TP 5
  343. .B \-p
  344. causes
  345. .I perl
  346. to assume the following loop around your script, which makes it iterate
  347. over filename arguments somewhat like \fIsed\fR:
  348. .nf
  349.  
  350. .ne 5
  351.     while (<>) {
  352.         .\|.\|.        # your script goes here
  353.     } continue {
  354.         print;
  355.     }
  356.  
  357. .fi
  358. Note that the lines are printed automatically.
  359. To suppress printing use the
  360. .B \-n
  361. switch.
  362. A
  363. .B \-p
  364. overrides a
  365. .B \-n
  366. switch.
  367. .TP 5
  368. .B \-P
  369. causes your script to be run through the C preprocessor before
  370. compilation by
  371. .IR perl .
  372. (Since both comments and cpp directives begin with the # character,
  373. you should avoid starting comments with any words recognized
  374. by the C preprocessor such as \*(L"if\*(R", \*(L"else\*(R" or \*(L"define\*(R".)
  375. .TP 5
  376. .B \-s
  377. enables some rudimentary switch parsing for switches on the command line
  378. after the script name but before any filename arguments (or before a \-\|\-).
  379. Any switch found there is removed from @ARGV and sets the corresponding variable in the
  380. .I perl
  381. script.
  382. The following script prints \*(L"true\*(R" if and only if the script is
  383. invoked with a \-xyz switch.
  384. .nf
  385.  
  386. .ne 2
  387.     #!/usr/bin/perl \-s
  388.     if ($xyz) { print "true\en"; }
  389.  
  390. .fi
  391. .TP 5
  392. .B \-S
  393. makes
  394. .I perl
  395. use the PATH environment variable to search for the script
  396. (unless the name of the script starts with a slash).
  397. Typically this is used to emulate #! startup on machines that don't
  398. support #!, in the following manner:
  399. .nf
  400.  
  401.     #!/usr/bin/perl
  402.     eval "exec /usr/bin/perl \-S $0 $*"
  403.         if $running_under_some_shell;
  404.  
  405. .fi
  406. The system ignores the first line and feeds the script to /bin/sh,
  407. which proceeds to try to execute the
  408. .I perl
  409. script as a shell script.
  410. The shell executes the second line as a normal shell command, and thus
  411. starts up the
  412. .I perl
  413. interpreter.
  414. On some systems $0 doesn't always contain the full pathname,
  415. so the
  416. .B \-S
  417. tells
  418. .I perl
  419. to search for the script if necessary.
  420. After
  421. .I perl
  422. locates the script, it parses the lines and ignores them because
  423. the variable $running_under_some_shell is never true.
  424. A better construct than $* would be ${1+"$@"}, which handles embedded spaces
  425. and such in the filenames, but doesn't work if the script is being interpreted
  426. by csh.
  427. In order to start up sh rather than csh, some systems may have to replace the
  428. #! line with a line containing just
  429. a colon, which will be politely ignored by perl.
  430. Other systems can't control that, and need a totally devious construct that
  431. will work under any of csh, sh or perl, such as the following:
  432. .nf
  433.  
  434. .ne 3
  435.     eval '(exit $?0)' && eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
  436.     & eval 'exec /usr/bin/perl -S $0 $argv:q'
  437.         if 0;
  438.  
  439. .fi
  440. .TP 5
  441. .B \-u
  442. causes
  443. .I perl
  444. to dump core after compiling your script.
  445. You can then take this core dump and turn it into an executable file
  446. by using the undump program (not supplied).
  447. This speeds startup at the expense of some disk space (which you can
  448. minimize by stripping the executable).
  449. (Still, a "hello world" executable comes out to about 200K on my machine.)
  450. If you are going to run your executable as a set-id program then you
  451. should probably compile it using taintperl rather than normal perl.
  452. If you want to execute a portion of your script before dumping, use the
  453. dump operator instead.
  454. Note: availability of undump is platform specific and may not be available
  455. for a specific port of perl.
  456. .TP 5
  457. .B \-U
  458. allows
  459. .I perl
  460. to do unsafe operations.
  461. Currently the only \*(L"unsafe\*(R" operations are the unlinking of directories while
  462. running as superuser, and running setuid programs with fatal taint checks
  463. turned into warnings.
  464. .TP 5
  465. .B \-v
  466. prints the version and patchlevel of your
  467. .I perl
  468. executable.
  469. .TP 5
  470. .B \-w
  471. prints warnings about identifiers that are mentioned only once, and scalar
  472. variables that are used before being set.
  473. Also warns about redefined subroutines, and references to undefined
  474. filehandles or filehandles opened readonly that you are attempting to
  475. write on.
  476. Also warns you if you use == on values that don't look like numbers, and if
  477. your subroutines recurse more than 100 deep.
  478. .TP 5
  479. .BI \-x directory
  480. tells
  481. .I perl
  482. that the script is embedded in a message.
  483. Leading garbage will be discarded until the first line that starts
  484. with #! and contains the string "perl".
  485. Any meaningful switches on that line will be applied (but only one
  486. group of switches, as with normal #! processing).
  487. If a directory name is specified, Perl will switch to that directory
  488. before running the script.
  489. The
  490. .B \-x
  491. switch only controls the the disposal of leading garbage.
  492. The script must be terminated with _\|_END_\|_ if there is trailing garbage
  493. to be ignored (the script can process any or all of the trailing garbage
  494. via the DATA filehandle if desired).
  495. .Sh "Data Types and Objects"
  496. .PP
  497. .I Perl
  498. has three data types: scalars, arrays of scalars, and
  499. associative arrays of scalars.
  500. Normal arrays are indexed by number, and associative arrays by string.
  501. .PP
  502. The interpretation of operations and values in perl sometimes
  503. depends on the requirements
  504. of the context around the operation or value.
  505. There are three major contexts: string, numeric and array.
  506. Certain operations return array values
  507. in contexts wanting an array, and scalar values otherwise.
  508. (If this is true of an operation it will be mentioned in the documentation
  509. for that operation.)
  510. Operations which return scalars don't care whether the context is looking
  511. for a string or a number, but
  512. scalar variables and values are interpreted as strings or numbers
  513. as appropriate to the context.
  514. A scalar is interpreted as TRUE in the boolean sense if it is not the null
  515. string or 0.
  516. Booleans returned by operators are 1 for true and 0 or \'\' (the null
  517. string) for false.
  518. .PP
  519. There are actually two varieties of null string: defined and undefined.
  520. Undefined null strings are returned when there is no real value for something,
  521. such as when there was an error, or at end of file, or when you refer
  522. to an uninitialized variable or element of an array.
  523. An undefined null string may become defined the first time you access it, but
  524. prior to that you can use the defined() operator to determine whether the
  525. value is defined or not.
  526. .PP
  527. References to scalar variables always begin with \*(L'$\*(R', even when referring
  528. to a scalar that is part of an array.
  529. Thus:
  530. .nf
  531.  
  532. .ne 3
  533.     $days    \h'|2i'# a simple scalar variable
  534.     $days[28]    \h'|2i'# 29th element of array @days
  535.     $days{\'Feb\'}\h'|2i'# one value from an associative array
  536.     $#days    \h'|2i'# last index of array @days
  537.  
  538. but entire arrays or array slices are denoted by \*(L'@\*(R':
  539.  
  540.     @days    \h'|2i'# ($days[0], $days[1],\|.\|.\|. $days[n])
  541.     @days[3,4,5]\h'|2i'# same as @days[3.\|.5]
  542.     @days{'a','c'}\h'|2i'# same as ($days{'a'},$days{'c'})
  543.  
  544. and entire associative arrays are denoted by \*(L'%\*(R':
  545.  
  546.     %days    \h'|2i'# (key1, val1, key2, val2 .\|.\|.)
  547. .fi
  548. .PP
  549. Any of these eight constructs may serve as an lvalue,
  550. that is, may be assigned to.
  551. (It also turns out that an assignment is itself an lvalue in
  552. certain contexts\*(--see examples under s, tr and chop.)
  553. Assignment to a scalar evaluates the righthand side in a scalar context,
  554. while assignment to an array or array slice evaluates the righthand side
  555. in an array context.
  556. .PP
  557. You may find the length of array @days by evaluating
  558. \*(L"$#days\*(R", as in
  559. .IR csh .
  560. (Actually, it's not the length of the array, it's the subscript of the last element, since there is (ordinarily) a 0th element.)
  561. Assigning to $#days changes the length of the array.
  562. Shortening an array by this method does not actually destroy any values.
  563. Lengthening an array that was previously shortened recovers the values that
  564. were in those elements.
  565. You can also gain some measure of efficiency by preextending an array that
  566. is going to get big.
  567. (You can also extend an array by assigning to an element that is off the
  568. end of the array.
  569. This differs from assigning to $#whatever in that intervening values
  570. are set to null rather than recovered.)
  571. You can truncate an array down to nothing by assigning the null list () to
  572. it.
  573. The following are exactly equivalent
  574. .nf
  575.  
  576.     @whatever = ();
  577.     $#whatever = $[ \- 1;
  578.  
  579. .fi
  580. .PP
  581. If you evaluate an array in a scalar context, it returns the length of
  582. the array.
  583. The following is always true:
  584. .nf
  585.  
  586.     scalar(@whatever) == $#whatever \- $[ + 1;
  587.  
  588. .fi
  589. If you evaluate an associative array in a scalar context, it returns
  590. a value which is true if and only if the array contains any elements.
  591. (If there are any elements, the value returned is a string consisting
  592. of the number of used buckets and the number of allocated buckets, separated
  593. by a slash.)
  594. .PP
  595. Multi-dimensional arrays are not directly supported, but see the discussion
  596. of the $; variable later for a means of emulating multiple subscripts with
  597. an associative array.
  598. You could also write a subroutine to turn multiple subscripts into a single
  599. subscript.
  600. .PP
  601. Every data type has its own namespace.
  602. You can, without fear of conflict, use the same name for a scalar variable,
  603. an array, an associative array, a filehandle, a subroutine name, and/or
  604. a label.
  605. Since variable and array references always start with \*(L'$\*(R', \*(L'@\*(R',
  606. or \*(L'%\*(R', the \*(L"reserved\*(R" words aren't in fact reserved
  607. with respect to variable names.
  608. (They ARE reserved with respect to labels and filehandles, however, which
  609. don't have an initial special character.
  610. Hint: you could say open(LOG,\'logfile\') rather than open(log,\'logfile\').
  611. Using uppercase filehandles also improves readability and protects you
  612. from conflict with future reserved words.)
  613. Case IS significant\*(--\*(L"FOO\*(R", \*(L"Foo\*(R" and \*(L"foo\*(R" are all
  614. different names.
  615. Names which start with a letter may also contain digits and underscores.
  616. Names which do not start with a letter are limited to one character,
  617. e.g. \*(L"$%\*(R" or \*(L"$$\*(R".
  618. (Most of the one character names have a predefined significance to
  619. .IR perl .
  620. More later.)
  621. .PP
  622. Numeric literals are specified in any of the usual floating point or
  623. integer formats:
  624. .nf
  625.  
  626. .ne 5
  627.     12345
  628.     12345.67
  629.     .23E-10
  630.     0xffff    # hex
  631.     0377    # octal
  632.  
  633. .fi
  634. String literals are delimited by either single or double quotes.
  635. They work much like shell quotes:
  636. double-quoted string literals are subject to backslash and variable
  637. substitution; single-quoted strings are not (except for \e\' and \e\e).
  638. The usual backslash rules apply for making characters such as newline, tab,
  639. etc., as well as some more exotic forms:
  640. .nf
  641.  
  642.     \et        tab
  643.     \en        newline
  644.     \er        return
  645.     \ef        form feed
  646.     \eb        backspace
  647.     \ea        alarm (bell)
  648.     \ee        escape
  649.     \e033        octal char
  650.     \ex1b        hex char
  651.     \ec[        control char
  652.     \el        lowercase next char
  653.     \eu        uppercase next char
  654.     \eL        lowercase till \eE
  655.     \eU        uppercase till \eE
  656.     \eE        end case modification
  657.  
  658. .fi
  659. You can also embed newlines directly in your strings, i.e. they can end on
  660. a different line than they begin.
  661. This is nice, but if you forget your trailing quote, the error will not be
  662. reported until
  663. .I perl
  664. finds another line containing the quote character, which
  665. may be much further on in the script.
  666. Variable substitution inside strings is limited to scalar variables, normal
  667. array values, and array slices.
  668. (In other words, identifiers beginning with $ or @, followed by an optional
  669. bracketed expression as a subscript.)
  670. The following code segment prints out \*(L"The price is $100.\*(R"
  671. .nf
  672.  
  673. .ne 2
  674.     $Price = \'$100\';\h'|3.5i'# not interpreted
  675.     print "The price is $Price.\e\|n";\h'|3.5i'# interpreted
  676.  
  677. .fi
  678. Note that you can put curly brackets around the identifier to delimit it
  679. from following alphanumerics.
  680. Also note that a single quoted string must be separated from a preceding
  681. word by a space, since single quote is a valid character in an identifier
  682. (see Packages).
  683. .PP
  684. Two special literals are _\|_LINE_\|_ and _\|_FILE_\|_, which represent the current
  685. line number and filename at that point in your program.
  686. They may only be used as separate tokens; they will not be interpolated
  687. into strings.
  688. In addition, the token _\|_END_\|_ may be used to indicate the logical end of the
  689. script before the actual end of file.
  690. Any following text is ignored (but may be read via the DATA filehandle).
  691. The two control characters ^D and ^Z are synonyms for _\|_END_\|_.
  692. .PP
  693. A word that doesn't have any other interpretation in the grammar will be
  694. treated as if it had single quotes around it.
  695. For this purpose, a word consists only of alphanumeric characters and underline,
  696. and must start with an alphabetic character.
  697. As with filehandles and labels, a bare word that consists entirely of
  698. lowercase letters risks conflict with future reserved words, and if you
  699. use the
  700. .B \-w
  701. switch, Perl will warn you about any such words.
  702. .PP
  703. Array values are interpolated into double-quoted strings by joining all the
  704. elements of the array with the delimiter specified in the $" variable,
  705. space by default.
  706. (Since in versions of perl prior to 3.0 the @ character was not a metacharacter
  707. in double-quoted strings, the interpolation of @array, $array[EXPR],
  708. @array[LIST], $array{EXPR}, or @array{LIST} only happens if array is
  709. referenced elsewhere in the program or is predefined.)
  710. The following are equivalent:
  711. .nf
  712.  
  713. .ne 4
  714.     $temp = join($",@ARGV);
  715.     system "echo $temp";
  716.  
  717.     system "echo @ARGV";
  718.  
  719. .fi
  720. Within search patterns (which also undergo double-quotish substitution)
  721. there is a bad ambiguity:  Is /$foo[bar]/ to be
  722. interpreted as /${foo}[bar]/ (where [bar] is a character class for the
  723. regular expression) or as /${foo[bar]}/ (where [bar] is the subscript to
  724. array @foo)?
  725. If @foo doesn't otherwise exist, then it's obviously a character class.
  726. If @foo exists, perl takes a good guess about [bar], and is almost always right.
  727. If it does guess wrong, or if you're just plain paranoid,
  728. you can force the correct interpretation with curly brackets as above.
  729. .PP
  730. A line-oriented form of quoting is based on the shell here-is syntax.
  731. Following a << you specify a string to terminate the quoted material, and all lines
  732. following the current line down to the terminating string are the value
  733. of the item.
  734. The terminating string may be either an identifier (a word), or some
  735. quoted text.
  736. If quoted, the type of quotes you use determines the treatment of the text,
  737. just as in regular quoting.
  738. An unquoted identifier works like double quotes.
  739. There must be no space between the << and the identifier.
  740. (If you put a space it will be treated as a null identifier, which is
  741. valid, and matches the first blank line\*(--see Merry Christmas example below.)
  742. The terminating string must appear by itself (unquoted and with no surrounding
  743. whitespace) on the terminating line.
  744. .nf
  745.  
  746.     print <<EOF;        # same as above
  747. The price is $Price.
  748. EOF
  749.  
  750.     print <<"EOF";        # same as above
  751. The price is $Price.
  752. EOF
  753.  
  754.     print << x 10;        # null identifier is delimiter
  755. Merry Christmas!
  756.  
  757.     print <<`EOC`;        # execute commands
  758. echo hi there
  759. echo lo there
  760. EOC
  761.  
  762.     print <<foo, <<bar;    # you can stack them
  763. I said foo.
  764. foo
  765. I said bar.
  766. bar
  767.  
  768. .fi
  769. Array literals are denoted by separating individual values by commas, and
  770. enclosing the list in parentheses:
  771. .nf
  772.  
  773.     (LIST)
  774.  
  775. .fi
  776. In a context not requiring an array value, the value of the array literal
  777. is the value of the final element, as in the C comma operator.
  778. For example,
  779. .nf
  780.  
  781. .ne 4
  782.     @foo = (\'cc\', \'\-E\', $bar);
  783.  
  784. assigns the entire array value to array foo, but
  785.  
  786.     $foo = (\'cc\', \'\-E\', $bar);
  787.  
  788. .fi
  789. assigns the value of variable bar to variable foo.
  790. Note that the value of an actual array in a scalar context is the length
  791. of the array; the following assigns to $foo the value 3:
  792. .nf
  793.  
  794. .ne 2
  795.     @foo = (\'cc\', \'\-E\', $bar);
  796.     $foo = @foo;        # $foo gets 3
  797.  
  798. .fi
  799. You may have an optional comma before the closing parenthesis of an
  800. array literal, so that you can say:
  801. .nf
  802.  
  803.     @foo = (
  804.     1,
  805.     2,
  806.     3,
  807.     );
  808.  
  809. .fi
  810. When a LIST is evaluated, each element of the list is evaluated in
  811. an array context, and the resulting array value is interpolated into LIST
  812. just as if each individual element were a member of LIST.  Thus arrays
  813. lose their identity in a LIST\*(--the list
  814.  
  815.     (@foo,@bar,&SomeSub)
  816.  
  817. contains all the elements of @foo followed by all the elements of @bar,
  818. followed by all the elements returned by the subroutine named SomeSub.
  819. .PP
  820. A list value may also be subscripted like a normal array.
  821. Examples:
  822. .nf
  823.  
  824.     $time = (stat($file))[8];    # stat returns array value
  825.     $digit = ('a','b','c','d','e','f')[$digit-10];
  826.     return (pop(@foo),pop(@foo))[0];
  827.  
  828. .fi
  829. .PP
  830. Array lists may be assigned to if and only if each element of the list
  831. is an lvalue:
  832. .nf
  833.  
  834.     ($a, $b, $c) = (1, 2, 3);
  835.  
  836.     ($map{\'red\'}, $map{\'blue\'}, $map{\'green\'}) = (0x00f, 0x0f0, 0xf00);
  837.  
  838. The final element may be an array or an associative array:
  839.  
  840.     ($a, $b, @rest) = split;
  841.     local($a, $b, %rest) = @_;
  842.  
  843. .fi
  844. You can actually put an array anywhere in the list, but the first array
  845. in the list will soak up all the values, and anything after it will get
  846. a null value.
  847. This may be useful in a local().
  848. .PP
  849. An associative array literal contains pairs of values to be interpreted
  850. as a key and a value:
  851. .nf
  852.  
  853. .ne 2
  854.     # same as map assignment above
  855.     %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
  856.  
  857. .fi
  858. Array assignment in a scalar context returns the number of elements
  859. produced by the expression on the right side of the assignment:
  860. .nf
  861.  
  862.     $x = (($foo,$bar) = (3,2,1));    # set $x to 3, not 2
  863.  
  864. .fi
  865. .PP
  866. There are several other pseudo-literals that you should know about.
  867. If a string is enclosed by backticks (grave accents), it first undergoes
  868. variable substitution just like a double quoted string.
  869. It is then interpreted as a command, and the output of that command
  870. is the value of the pseudo-literal, like in a shell.
  871. In a scalar context, a single string consisting of all the output is
  872. returned.
  873. In an array context, an array of values is returned, one for each line
  874. of output.
  875. (You can set $/ to use a different line terminator.)
  876. The command is executed each time the pseudo-literal is evaluated.
  877. The status value of the command is returned in $? (see Predefined Names
  878. for the interpretation of $?).
  879. Unlike in \f2csh\f1, no translation is done on the return
  880. data\*(--newlines remain newlines.
  881. Unlike in any of the shells, single quotes do not hide variable names
  882. in the command from interpretation.
  883. To pass a $ through to the shell you need to hide it with a backslash.
  884. .PP
  885. Evaluating a filehandle in angle brackets yields the next line
  886. from that file (newline included, so it's never false until EOF, at
  887. which time an undefined value is returned).
  888. Ordinarily you must assign that value to a variable,
  889. but there is one situation where an automatic assignment happens.
  890. If (and only if) the input symbol is the only thing inside the conditional of a
  891. .I while
  892. loop, the value is
  893. automatically assigned to the variable \*(L"$_\*(R".
  894. (This may seem like an odd thing to you, but you'll use the construct
  895. in almost every
  896. .I perl
  897. script you write.)
  898. Anyway, the following lines are equivalent to each other:
  899. .nf
  900.  
  901. .ne 5
  902.     while ($_ = <STDIN>) { print; }
  903.     while (<STDIN>) { print; }
  904.     for (\|;\|<STDIN>;\|) { print; }
  905.     print while $_ = <STDIN>;
  906.     print while <STDIN>;
  907.  
  908. .fi
  909. The filehandles
  910. .IR STDIN ,
  911. .I STDOUT
  912. and
  913. .I STDERR
  914. are predefined.
  915. (The filehandles
  916. .IR stdin ,
  917. .I stdout
  918. and
  919. .I stderr
  920. will also work except in packages, where they would be interpreted as
  921. local identifiers rather than global.)
  922. Additional filehandles may be created with the
  923. .I open
  924. function.
  925. .PP
  926. If a <FILEHANDLE> is used in a context that is looking for an array, an array
  927. consisting of all the input lines is returned, one line per array element.
  928. It's easy to make a LARGE data space this way, so use with care.
  929. .PP
  930. The null filehandle <> is special and can be used to emulate the behavior of
  931. \fIsed\fR and \fIawk\fR.
  932. Input from <> comes either from standard input, or from each file listed on
  933. the command line.
  934. Here's how it works: the first time <> is evaluated, the ARGV array is checked,
  935. and if it is null, $ARGV[0] is set to \'-\', which when opened gives you standard
  936. input.
  937. The ARGV array is then processed as a list of filenames.
  938. The loop
  939. .nf
  940.  
  941. .ne 3
  942.     while (<>) {
  943.         .\|.\|.            # code for each line
  944.     }
  945.  
  946. .ne 10
  947. is equivalent to
  948.  
  949.     unshift(@ARGV, \'\-\') \|if \|$#ARGV < $[;
  950.     while ($ARGV = shift) {
  951.         open(ARGV, $ARGV);
  952.         while (<ARGV>) {
  953.             .\|.\|.        # code for each line
  954.         }
  955.     }
  956.  
  957. .fi
  958. except that it isn't as cumbersome to say.
  959. It really does shift array ARGV and put the current filename into
  960. variable ARGV.
  961. It also uses filehandle ARGV internally.
  962. You can modify @ARGV before the first <> as long as you leave the first
  963. filename at the beginning of the array.
  964. Line numbers ($.) continue as if the input was one big happy file.
  965. (But see example under eof for how to reset line numbers on each file.)
  966. .PP
  967. .ne 5
  968. If you want to set @ARGV to your own list of files, go right ahead.
  969. If you want to pass switches into your script, you can
  970. put a loop on the front like this:
  971. .nf
  972.  
  973. .ne 10
  974.     while ($_ = $ARGV[0], /\|^\-/\|) {
  975.         shift;
  976.         last if /\|^\-\|\-$\|/\|;
  977.         /\|^\-D\|(.*\|)/ \|&& \|($debug = $1);
  978.         /\|^\-v\|/ \|&& \|$verbose++;
  979.         .\|.\|.        # other switches
  980.     }
  981.     while (<>) {
  982.         .\|.\|.        # code for each line
  983.     }
  984.  
  985. .fi
  986. The <> symbol will return FALSE only once.
  987. If you call it again after this it will assume you are processing another
  988. @ARGV list, and if you haven't set @ARGV, will input from
  989. .IR STDIN .
  990. .PP
  991. If the string inside the angle brackets is a reference to a scalar variable
  992. (e.g. <$foo>),
  993. then that variable contains the name of the filehandle to input from.
  994. .PP
  995. If the string inside angle brackets is not a filehandle, it is interpreted
  996. as a filename pattern to be globbed, and either an array of filenames or the
  997. next filename in the list is returned, depending on context.
  998. One level of $ interpretation is done first, but you can't say <$foo>
  999. because that's an indirect filehandle as explained in the previous
  1000. paragraph.
  1001. You could insert curly brackets to force interpretation as a
  1002. filename glob: <${foo}>.
  1003. Example:
  1004. .nf
  1005.  
  1006. .ne 3
  1007.     while (<*.c>) {
  1008.         chmod 0644, $_;
  1009.     }
  1010.  
  1011. is equivalent to
  1012.  
  1013. .ne 5
  1014.     open(foo, "echo *.c | tr \-s \' \et\er\ef\' \'\e\e012\e\e012\e\e012\e\e012\'|");
  1015.     while (<foo>) {
  1016.         chop;
  1017.         chmod 0644, $_;
  1018.     }
  1019.  
  1020. .fi
  1021. In fact, it's currently implemented that way.
  1022. (Which means it will not work on filenames with spaces in them unless
  1023. you have /bin/csh on your machine.)
  1024. Of course, the shortest way to do the above is:
  1025. .nf
  1026.  
  1027.     chmod 0644, <*.c>;
  1028.  
  1029. .fi
  1030. .Sh "Syntax"
  1031. .PP
  1032. A
  1033. .I perl
  1034. script consists of a sequence of declarations and commands.
  1035. The only things that need to be declared in
  1036. .I perl
  1037. are report formats and subroutines.
  1038. See the sections below for more information on those declarations.
  1039. All uninitialized user-created objects are assumed to
  1040. start with a null or 0 value until they
  1041. are defined by some explicit operation such as assignment.
  1042. The sequence of commands is executed just once, unlike in
  1043. .I sed
  1044. and
  1045. .I awk
  1046. scripts, where the sequence of commands is executed for each input line.
  1047. While this means that you must explicitly loop over the lines of your input file
  1048. (or files), it also means you have much more control over which files and which
  1049. lines you look at.
  1050. (Actually, I'm lying\*(--it is possible to do an implicit loop with either the
  1051. .B \-n
  1052. or
  1053. .B \-p
  1054. switch.)
  1055. .PP
  1056. A declaration can be put anywhere a command can, but has no effect on the
  1057. execution of the primary sequence of commands\*(--declarations all take effect
  1058. at compile time.
  1059. Typically all the declarations are put at the beginning or the end of the script.
  1060. .PP
  1061. .I Perl
  1062. is, for the most part, a free-form language.
  1063. (The only exception to this is format declarations, for fairly obvious reasons.)
  1064. Comments are indicated by the # character, and extend to the end of the line.
  1065. If you attempt to use /* */ C comments, it will be interpreted either as
  1066. division or pattern matching, depending on the context.
  1067. So don't do that.
  1068. .Sh "Compound statements"
  1069. In
  1070. .IR perl ,
  1071. a sequence of commands may be treated as one command by enclosing it
  1072. in curly brackets.
  1073. We will call this a BLOCK.
  1074. .PP
  1075. The following compound commands may be used to control flow:
  1076. .nf
  1077.  
  1078. .ne 4
  1079.     if (EXPR) BLOCK
  1080.     if (EXPR) BLOCK else BLOCK
  1081.     if (EXPR) BLOCK elsif (EXPR) BLOCK .\|.\|. else BLOCK
  1082.     LABEL while (EXPR) BLOCK
  1083.     LABEL while (EXPR) BLOCK continue BLOCK
  1084.     LABEL for (EXPR; EXPR; EXPR) BLOCK
  1085.     LABEL foreach VAR (ARRAY) BLOCK
  1086.     LABEL BLOCK continue BLOCK
  1087.  
  1088. .fi
  1089. Note that, unlike C and Pascal, these are defined in terms of BLOCKs, not
  1090. statements.
  1091. This means that the curly brackets are \fIrequired\fR\*(--no dangling statements allowed.
  1092. If you want to write conditionals without curly brackets there are several
  1093. other ways to do it.
  1094. The following all do the same thing:
  1095. .nf
  1096.  
  1097. .ne 5
  1098.     if (!open(foo)) { die "Can't open $foo: $!"; }
  1099.     die "Can't open $foo: $!" unless open(foo);
  1100.     open(foo) || die "Can't open $foo: $!";    # foo or bust!
  1101.     open(foo) ? \'hi mom\' : die "Can't open $foo: $!";
  1102.                 # a bit exotic, that last one
  1103.  
  1104. .fi
  1105. .PP
  1106. The
  1107. .I if
  1108. statement is straightforward.
  1109. Since BLOCKs are always bounded by curly brackets, there is never any
  1110. ambiguity about which
  1111. .I if
  1112. an
  1113. .I else
  1114. goes with.
  1115. If you use
  1116. .I unless
  1117. in place of
  1118. .IR if ,
  1119. the sense of the test is reversed.
  1120. .PP
  1121. The
  1122. .I while
  1123. statement executes the block as long as the expression is true
  1124. (does not evaluate to the null string or 0).
  1125. The LABEL is optional, and if present, consists of an identifier followed by
  1126. a colon.
  1127. The LABEL identifies the loop for the loop control statements
  1128. .IR next ,
  1129. .IR last ,
  1130. and
  1131. .I redo
  1132. (see below).
  1133. If there is a
  1134. .I continue
  1135. BLOCK, it is always executed just before
  1136. the conditional is about to be evaluated again, similarly to the third part
  1137. of a
  1138. .I for
  1139. loop in C.
  1140. Thus it can be used to increment a loop variable, even when the loop has
  1141. been continued via the
  1142. .I next
  1143. statement (similar to the C \*(L"continue\*(R" statement).
  1144. .PP
  1145. If the word
  1146. .I while
  1147. is replaced by the word
  1148. .IR until ,
  1149. the sense of the test is reversed, but the conditional is still tested before
  1150. the first iteration.
  1151. .PP
  1152. In either the
  1153. .I if
  1154. or the
  1155. .I while
  1156. statement, you may replace \*(L"(EXPR)\*(R" with a BLOCK, and the conditional
  1157. is true if the value of the last command in that block is true.
  1158. .PP
  1159. The
  1160. .I for
  1161. loop works exactly like the corresponding
  1162. .I while
  1163. loop:
  1164. .nf
  1165.  
  1166. .ne 12
  1167.     for ($i = 1; $i < 10; $i++) {
  1168.         .\|.\|.
  1169.     }
  1170.  
  1171. is the same as
  1172.  
  1173.     $i = 1;
  1174.     while ($i < 10) {
  1175.         .\|.\|.
  1176.     } continue {
  1177.         $i++;
  1178.     }
  1179. .fi
  1180. .PP
  1181. The foreach loop iterates over a normal array value and sets the variable
  1182. VAR to be each element of the array in turn.
  1183. The variable is implicitly local to the loop, and regains its former value
  1184. upon exiting the loop.
  1185. The \*(L"foreach\*(R" keyword is actually identical to the \*(L"for\*(R" keyword,
  1186. so you can use \*(L"foreach\*(R" for readability or \*(L"for\*(R" for brevity.
  1187. If VAR is omitted, $_ is set to each value.
  1188. If ARRAY is an actual array (as opposed to an expression returning an array
  1189. value), you can modify each element of the array
  1190. by modifying VAR inside the loop.
  1191. Examples:
  1192. .nf
  1193.  
  1194. .ne 5
  1195.     for (@ary) { s/foo/bar/; }
  1196.  
  1197.     foreach $elem (@elements) {
  1198.         $elem *= 2;
  1199.     }
  1200.  
  1201. .ne 3
  1202.     for ((10,9,8,7,6,5,4,3,2,1,\'BOOM\')) {
  1203.         print $_, "\en"; sleep(1);
  1204.     }
  1205.  
  1206.     for (1..15) { print "Merry Christmas\en"; }
  1207.  
  1208. .ne 3
  1209.     foreach $item (split(/:[\e\e\en:]*/, $ENV{\'TERMCAP\'})) {
  1210.         print "Item: $item\en";
  1211.     }
  1212.  
  1213. .fi
  1214. .PP
  1215. The BLOCK by itself (labeled or not) is equivalent to a loop that executes
  1216. once.
  1217. Thus you can use any of the loop control statements in it to leave or
  1218. restart the block.
  1219. The
  1220. .I continue
  1221. block is optional.
  1222. This construct is particularly nice for doing case structures.
  1223. .nf
  1224.  
  1225. .ne 6
  1226.     foo: {
  1227.         if (/^abc/) { $abc = 1; last foo; }
  1228.         if (/^def/) { $def = 1; last foo; }
  1229.         if (/^xyz/) { $xyz = 1; last foo; }
  1230.         $nothing = 1;
  1231.     }
  1232.  
  1233. .fi
  1234. There is no official switch statement in perl, because there
  1235. are already several ways to write the equivalent.
  1236. In addition to the above, you could write
  1237. .nf
  1238.  
  1239. .ne 6
  1240.     foo: {
  1241.         $abc = 1, last foo  if /^abc/;
  1242.         $def = 1, last foo  if /^def/;
  1243.         $xyz = 1, last foo  if /^xyz/;
  1244.         $nothing = 1;
  1245.     }
  1246.  
  1247. or
  1248.  
  1249. .ne 6
  1250.     foo: {
  1251.         /^abc/ && do { $abc = 1; last foo; };
  1252.         /^def/ && do { $def = 1; last foo; };
  1253.         /^xyz/ && do { $xyz = 1; last foo; };
  1254.         $nothing = 1;
  1255.     }
  1256.  
  1257. or
  1258.  
  1259. .ne 6
  1260.     foo: {
  1261.         /^abc/ && ($abc = 1, last foo);
  1262.         /^def/ && ($def = 1, last foo);
  1263.         /^xyz/ && ($xyz = 1, last foo);
  1264.         $nothing = 1;
  1265.     }
  1266.  
  1267. or even
  1268.  
  1269. .ne 8
  1270.     if (/^abc/)
  1271.         { $abc = 1; }
  1272.     elsif (/^def/)
  1273.         { $def = 1; }
  1274.     elsif (/^xyz/)
  1275.         { $xyz = 1; }
  1276.     else
  1277.         {$nothing = 1;}
  1278.  
  1279. .fi
  1280. As it happens, these are all optimized internally to a switch structure,
  1281. so perl jumps directly to the desired statement, and you needn't worry
  1282. about perl executing a lot of unnecessary statements when you have a string
  1283. of 50 elsifs, as long as you are testing the same simple scalar variable
  1284. using ==, eq, or pattern matching as above.
  1285. (If you're curious as to whether the optimizer has done this for a particular
  1286. case statement, you can use the \-D1024 switch to list the syntax tree
  1287. before execution.)
  1288. .Sh "Simple statements"
  1289. The only kind of simple statement is an expression evaluated for its side
  1290. effects.
  1291. Every expression (simple statement) must be terminated with a semicolon.
  1292. Note that this is like C, but unlike Pascal (and
  1293. .IR awk ).
  1294. .PP
  1295. Any simple statement may optionally be followed by a
  1296. single modifier, just before the terminating semicolon.
  1297. The possible modifiers are:
  1298. .nf
  1299.  
  1300. .ne 4
  1301.     if EXPR
  1302.     unless EXPR
  1303.     while EXPR
  1304.     until EXPR
  1305.  
  1306. .fi
  1307. The
  1308. .I if
  1309. and
  1310. .I unless
  1311. modifiers have the expected semantics.
  1312. The
  1313. .I while
  1314. and
  1315. .I until
  1316. modifiers also have the expected semantics (conditional evaluated first),
  1317. except when applied to a do-BLOCK or a do-SUBROUTINE command,
  1318. in which case the block executes once before the conditional is evaluated.
  1319. This is so that you can write loops like:
  1320. .nf
  1321.  
  1322. .ne 4
  1323.     do {
  1324.         $_ = <STDIN>;
  1325.         .\|.\|.
  1326.     } until $_ \|eq \|".\|\e\|n";
  1327.  
  1328. .fi
  1329. (See the
  1330. .I do
  1331. operator below.  Note also that the loop control commands described later will
  1332. NOT work in this construct, since modifiers don't take loop labels.
  1333. Sorry.)
  1334. .Sh "Expressions"
  1335. Since
  1336. .I perl
  1337. expressions work almost exactly like C expressions, only the differences
  1338. will be mentioned here.
  1339. .PP
  1340. Here's what
  1341. .I perl
  1342. has that C doesn't:
  1343. .Ip ** 8 2
  1344. The exponentiation operator.
  1345. .Ip **= 8
  1346. The exponentiation assignment operator.
  1347. .Ip (\|) 8 3
  1348. The null list, used to initialize an array to null.
  1349. .Ip . 8
  1350. Concatenation of two strings.
  1351. .Ip .= 8
  1352. The concatenation assignment operator.
  1353. .Ip eq 8
  1354. String equality (== is numeric equality).
  1355. For a mnemonic just think of \*(L"eq\*(R" as a string.
  1356. (If you are used to the
  1357. .I awk
  1358. behavior of using == for either string or numeric equality
  1359. based on the current form of the comparands, beware!
  1360. You must be explicit here.)
  1361. .Ip ne 8
  1362. String inequality (!= is numeric inequality).
  1363. .Ip lt 8
  1364. String less than.
  1365. .Ip gt 8
  1366. String greater than.
  1367. .Ip le 8
  1368. String less than or equal.
  1369. .Ip ge 8
  1370. String greater than or equal.
  1371. .Ip cmp 8
  1372. String comparison, returning -1, 0, or 1.
  1373. .Ip <=> 8
  1374. Numeric comparison, returning -1, 0, or 1.
  1375. .Ip =~ 8 2
  1376. Certain operations search or modify the string \*(L"$_\*(R" by default.
  1377. This operator makes that kind of operation work on some other string.
  1378. The right argument is a search pattern, substitution, or translation.
  1379. The left argument is what is supposed to be searched, substituted, or
  1380. translated instead of the default \*(L"$_\*(R".
  1381. The return value indicates the success of the operation.
  1382. (If the right argument is an expression other than a search pattern,
  1383. substitution, or translation, it is interpreted as a search pattern
  1384. at run time.
  1385. This is less efficient than an explicit search, since the pattern must
  1386. be compiled every time the expression is evaluated.)
  1387. The precedence of this operator is lower than unary minus and autoincrement/decrement, but higher than everything else.
  1388. .Ip !~ 8
  1389. Just like =~ except the return value is negated.
  1390. .Ip x 8
  1391. The repetition operator.
  1392. Returns a string consisting of the left operand repeated the
  1393. number of times specified by the right operand.
  1394. In an array context, if the left operand is a list in parens, it repeats
  1395. the list.
  1396. .nf
  1397.  
  1398.     print \'\-\' x 80;        # print row of dashes
  1399.     print \'\-\' x80;        # illegal, x80 is identifier
  1400.  
  1401.     print "\et" x ($tab/8), \' \' x ($tab%8);    # tab over
  1402.  
  1403.     @ones = (1) x 80;        # an array of 80 1's
  1404.     @ones = (5) x @ones;        # set all elements to 5
  1405.  
  1406. .fi
  1407. .Ip x= 8
  1408. The repetition assignment operator.
  1409. Only works on scalars.
  1410. .Ip .\|. 8
  1411. The range operator, which is really two different operators depending
  1412. on the context.
  1413. In an array context, returns an array of values counting (by ones)
  1414. from the left value to the right value.
  1415. This is useful for writing \*(L"for (1..10)\*(R" loops and for doing
  1416. slice operations on arrays.
  1417. .Sp
  1418. In a scalar context, .\|. returns a boolean value.
  1419. The operator is bistable, like a flip-flop..
  1420. Each .\|. operator maintains its own boolean state.
  1421. It is false as long as its left operand is false.
  1422. Once the left operand is true, the range operator stays true
  1423. until the right operand is true,
  1424. AFTER which the range operator becomes false again.
  1425. (It doesn't become false till the next time the range operator is evaluated.
  1426. It can become false on the same evaluation it became true, but it still returns
  1427. true once.)
  1428. The right operand is not evaluated while the operator is in the \*(L"false\*(R" state,
  1429. and the left operand is not evaluated while the operator is in the \*(L"true\*(R" state.
  1430. The scalar .\|. operator is primarily intended for doing line number ranges
  1431. after
  1432. the fashion of \fIsed\fR or \fIawk\fR.
  1433. The precedence is a little lower than || and &&.
  1434. The value returned is either the null string for false, or a sequence number
  1435. (beginning with 1) for true.
  1436. The sequence number is reset for each range encountered.
  1437. The final sequence number in a range has the string \'E0\' appended to it, which
  1438. doesn't affect its numeric value, but gives you something to search for if you
  1439. want to exclude the endpoint.
  1440. You can exclude the beginning point by waiting for the sequence number to be
  1441. greater than 1.
  1442. If either operand of scalar .\|. is static, that operand is implicitly compared
  1443. to the $. variable, the current line number.
  1444. Examples:
  1445. .nf
  1446.  
  1447. .ne 6
  1448. As a scalar operator:
  1449.     if (101 .\|. 200) { print; }    # print 2nd hundred lines
  1450.  
  1451.     next line if (1 .\|. /^$/);    # skip header lines
  1452.  
  1453.     s/^/> / if (/^$/ .\|. eof());    # quote body
  1454.  
  1455. .ne 4
  1456. As an array operator:
  1457.     for (101 .\|. 200) { print; }    # print $_ 100 times
  1458.  
  1459.     @foo = @foo[$[ .\|. $#foo];    # an expensive no-op
  1460.     @foo = @foo[$#foo-4 .\|. $#foo];    # slice last 5 items
  1461.  
  1462. .fi
  1463. .Ip \-x 8
  1464. A file test.
  1465. This unary operator takes one argument, either a filename or a filehandle,
  1466. and tests the associated file to see if something is true about it.
  1467. If the argument is omitted, tests $_, except for \-t, which tests
  1468. .IR STDIN .
  1469. It returns 1 for true and \'\' for false, or the undefined value if the
  1470. file doesn't exist.
  1471. Precedence is higher than logical and relational operators, but lower than
  1472. arithmetic operators.
  1473. The operator may be any of:
  1474. .nf
  1475.     \-r    File is readable by effective uid.
  1476.     \-w    File is writable by effective uid.
  1477.     \-x    File is executable by effective uid.
  1478.     \-o    File is owned by effective uid.
  1479.     \-R    File is readable by real uid.
  1480.     \-W    File is writable by real uid.
  1481.     \-X    File is executable by real uid.
  1482.     \-O    File is owned by real uid.
  1483.     \-e    File exists.
  1484.     \-z    File has zero size.
  1485.     \-s    File has non-zero size (returns size).
  1486.     \-f    File is a plain file.
  1487.     \-d    File is a directory.
  1488.     \-l    File is a symbolic link.
  1489.     \-p    File is a named pipe (FIFO).
  1490.     \-S    File is a socket.
  1491.     \-b    File is a block special file.
  1492.     \-c    File is a character special file.
  1493.     \-u    File has setuid bit set.
  1494.     \-g    File has setgid bit set.
  1495.     \-k    File has sticky bit set.
  1496.     \-t    Filehandle is opened to a tty.
  1497.     \-T    File is a text file.
  1498.     \-B    File is a binary file (opposite of \-T).
  1499.     \-M    Age of file in days when script started.
  1500.     \-A    Same for access time.
  1501.     \-C    Same for inode change time.
  1502.  
  1503. .fi
  1504. The interpretation of the file permission operators \-r, \-R, \-w, \-W, \-x and \-X
  1505. is based solely on the mode of the file and the uids and gids of the user.
  1506. There may be other reasons you can't actually read, write or execute the file.
  1507. Also note that, for the superuser, \-r, \-R, \-w and \-W always return 1, and 
  1508. \-x and \-X return 1 if any execute bit is set in the mode.
  1509. Scripts run by the superuser may thus need to do a stat() in order to determine
  1510. the actual mode of the file, or temporarily set the uid to something else.
  1511. .Sp
  1512. Example:
  1513. .nf
  1514. .ne 7
  1515.     
  1516.     while (<>) {
  1517.         chop;
  1518.         next unless \-f $_;    # ignore specials
  1519.         .\|.\|.
  1520.     }
  1521.  
  1522. .fi
  1523. Note that \-s/a/b/ does not do a negated substitution.
  1524. Saying \-exp($foo) still works as expected, however\*(--only single letters
  1525. following a minus are interpreted as file tests.
  1526. .Sp
  1527. The \-T and \-B switches work as follows.
  1528. The first block or so of the file is examined for odd characters such as
  1529. strange control codes or metacharacters.
  1530. If too many odd characters (>10%) are found, it's a \-B file, otherwise it's a \-T file.
  1531. Also, any file containing null in the first block is considered a binary file.
  1532. If \-T or \-B is used on a filehandle, the current stdio buffer is examined
  1533. rather than the first block.
  1534. Both \-T and \-B return TRUE on a null file, or a file at EOF when testing
  1535. a filehandle.
  1536. .PP
  1537. If any of the file tests (or either stat operator) are given the special
  1538. filehandle consisting of a solitary underline, then the stat structure
  1539. of the previous file test (or stat operator) is used, saving a system
  1540. call.
  1541. (This doesn't work with \-t, and you need to remember that lstat and -l
  1542. will leave values in the stat structure for the symbolic link, not the
  1543. real file.)
  1544. Example:
  1545. .nf
  1546.  
  1547.     print "Can do.\en" if -r $a || -w _ || -x _;
  1548.  
  1549. .ne 9
  1550.     stat($filename);
  1551.     print "Readable\en" if -r _;
  1552.     print "Writable\en" if -w _;
  1553.     print "Executable\en" if -x _;
  1554.     print "Setuid\en" if -u _;
  1555.     print "Setgid\en" if -g _;
  1556.     print "Sticky\en" if -k _;
  1557.     print "Text\en" if -T _;
  1558.     print "Binary\en" if -B _;
  1559.  
  1560. .fi
  1561. .PP
  1562. Here is what C has that
  1563. .I perl
  1564. doesn't:
  1565. .Ip "unary &" 12
  1566. Address-of operator.
  1567. .Ip "unary *" 12
  1568. Dereference-address operator.
  1569. .Ip "(TYPE)" 12
  1570. Type casting operator.
  1571. .PP
  1572. Like C,
  1573. .I perl
  1574. does a certain amount of expression evaluation at compile time, whenever
  1575. it determines that all of the arguments to an operator are static and have
  1576. no side effects.
  1577. In particular, string concatenation happens at compile time between literals that don't do variable substitution.
  1578. Backslash interpretation also happens at compile time.
  1579. You can say
  1580. .nf
  1581.  
  1582. .ne 2
  1583.     \'Now is the time for all\' . "\|\e\|n" .
  1584.     \'good men to come to.\'
  1585.  
  1586. .fi
  1587. and this all reduces to one string internally.
  1588. .PP
  1589. The autoincrement operator has a little extra built-in magic to it.
  1590. If you increment a variable that is numeric, or that has ever been used in
  1591. a numeric context, you get a normal increment.
  1592. If, however, the variable has only been used in string contexts since it
  1593. was set, and has a value that is not null and matches the
  1594. pattern /^[a\-zA\-Z]*[0\-9]*$/, the increment is done
  1595. as a string, preserving each character within its range, with carry:
  1596. .nf
  1597.  
  1598.     print ++($foo = \'99\');    # prints \*(L'100\*(R'
  1599.     print ++($foo = \'a0\');    # prints \*(L'a1\*(R'
  1600.     print ++($foo = \'Az\');    # prints \*(L'Ba\*(R'
  1601.     print ++($foo = \'zz\');    # prints \*(L'aaa\*(R'
  1602.  
  1603. .fi
  1604. The autodecrement is not magical.
  1605. .PP
  1606. The range operator (in an array context) makes use of the magical
  1607. autoincrement algorithm if the minimum and maximum are strings.
  1608. You can say
  1609.  
  1610.     @alphabet = (\'A\' .. \'Z\');
  1611.  
  1612. to get all the letters of the alphabet, or
  1613.  
  1614.     $hexdigit = (0 .. 9, \'a\' .. \'f\')[$num & 15];
  1615.  
  1616. to get a hexadecimal digit, or
  1617.  
  1618.     @z2 = (\'01\' .. \'31\');  print @z2[$mday];
  1619.  
  1620. to get dates with leading zeros.
  1621. (If the final value specified is not in the sequence that the magical increment
  1622. would produce, the sequence goes until the next value would be longer than
  1623. the final value specified.)
  1624. .PP
  1625. The || and && operators differ from C's in that, rather than returning 0 or 1,
  1626. they return the last value evaluated. 
  1627. Thus, a portable way to find out the home directory might be:
  1628. .nf
  1629.  
  1630.     $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
  1631.         (getpwuid($<))[7] || die "You're homeless!\en";
  1632.  
  1633. .fi
  1634. .PP
  1635. Along with the literals and variables mentioned earlier,
  1636. the operations in the following section can serve as terms in an expression.
  1637. Some of these operations take a LIST as an argument.
  1638. Such a list can consist of any combination of scalar arguments or array values;
  1639. the array values will be included in the list as if each individual element were
  1640. interpolated at that point in the list, forming a longer single-dimensional
  1641. array value.
  1642. Elements of the LIST should be separated by commas.
  1643. If an operation is listed both with and without parentheses around its
  1644. arguments, it means you can either use it as a unary operator or
  1645. as a function call.
  1646. To use it as a function call, the next token on the same line must
  1647. be a left parenthesis.
  1648. (There may be intervening white space.)
  1649. Such a function then has highest precedence, as you would expect from
  1650. a function.
  1651. If any token other than a left parenthesis follows, then it is a
  1652. unary operator, with a precedence depending only on whether it is a LIST
  1653. operator or not.
  1654. LIST operators have lowest precedence.
  1655. All other unary operators have a precedence greater than relational operators
  1656. but less than arithmetic operators.
  1657. See the section on Precedence.
  1658. .Ip "/PATTERN/" 8 4
  1659. See m/PATTERN/.
  1660. .Ip "?PATTERN?" 8 4
  1661. This is just like the /pattern/ search, except that it matches only once between
  1662. calls to the
  1663. .I reset
  1664. operator.
  1665. This is a useful optimization when you only want to see the first occurrence of
  1666. something in each file of a set of files, for instance.
  1667. Only ?? patterns local to the current package are reset.
  1668. .Ip "accept(NEWSOCKET,GENERICSOCKET)" 8 2
  1669. Does the same thing that the accept system call does.
  1670. Returns true if it succeeded, false otherwise.
  1671. See example in section on Interprocess Communication.
  1672. .Ip "alarm(SECONDS)" 8 4
  1673. .Ip "alarm SECONDS" 8
  1674. Arranges to have a SIGALRM delivered to this process after the specified number
  1675. of seconds (minus 1, actually) have elapsed.  Thus, alarm(15) will cause
  1676. a SIGALRM at some point more than 14 seconds in the future.
  1677. Only one timer may be counting at once.  Each call disables the previous
  1678. timer, and an argument of 0 may be supplied to cancel the previous timer
  1679. without starting a new one.
  1680. The returned value is the amount of time remaining on the previous timer.
  1681. .Ip "atan2(Y,X)" 8 2
  1682. Returns the arctangent of Y/X in the range
  1683. .if t \-\(*p to \(*p.
  1684. .if n \-PI to PI.
  1685. .Ip "bind(SOCKET,NAME)" 8 2
  1686. Does the same thing that the bind system call does.
  1687. Returns true if it succeeded, false otherwise.
  1688. NAME should be a packed address of the proper type for the socket.
  1689. See example in section on Interprocess Communication.
  1690. .Ip "binmode(FILEHANDLE)" 8 4
  1691. .Ip "binmode FILEHANDLE" 8 4
  1692. Arranges for the file to be read in \*(L"binary\*(R" mode in operating systems
  1693. that distinguish between binary and text files.
  1694. Files that are not read in binary mode have CR LF sequences translated
  1695. to LF on input and LF translated to CR LF on output.
  1696. Binmode has no effect under Unix.
  1697. If FILEHANDLE is an expression, the value is taken as the name of
  1698. the filehandle.
  1699. .Ip "caller(EXPR)"
  1700. .Ip "caller"
  1701. Returns the context of the current subroutine call:
  1702. .nf
  1703.  
  1704.     ($package,$filename,$line) = caller;
  1705.  
  1706. .fi
  1707. With EXPR, returns some extra information that the debugger uses to print
  1708. a stack trace.  The value of EXPR indicates how many call frames to go
  1709. back before the current one.
  1710. .Ip "chdir(EXPR)" 8 2
  1711. .Ip "chdir EXPR" 8 2
  1712. Changes the working directory to EXPR, if possible.
  1713. If EXPR is omitted, changes to home directory.
  1714. Returns 1 upon success, 0 otherwise.
  1715. See example under
  1716. .IR die .
  1717. .Ip "chmod(LIST)" 8 2
  1718. .Ip "chmod LIST" 8 2
  1719. Changes the permissions of a list of files.
  1720. The first element of the list must be the numerical mode.
  1721. Returns the number of files successfully changed.
  1722. .nf
  1723.  
  1724. .ne 2
  1725.     $cnt = chmod 0755, \'foo\', \'bar\';
  1726.     chmod 0755, @executables;
  1727.  
  1728. .fi
  1729. .Ip "chop(LIST)" 8 7
  1730. .Ip "chop(VARIABLE)" 8
  1731. .Ip "chop VARIABLE" 8
  1732. .Ip "chop" 8
  1733. Chops off the last character of a string and returns the character chopped.
  1734. It's used primarily to remove the newline from the end of an input record,
  1735. but is much more efficient than s/\en// because it neither scans nor copies
  1736. the string.
  1737. If VARIABLE is omitted, chops $_.
  1738. Example:
  1739. .nf
  1740.  
  1741. .ne 5
  1742.     while (<>) {
  1743.         chop;    # avoid \en on last field
  1744.         @array = split(/:/);
  1745.         .\|.\|.
  1746.     }
  1747.  
  1748. .fi
  1749. You can actually chop anything that's an lvalue, including an assignment:
  1750. .nf
  1751.  
  1752.     chop($cwd = \`pwd\`);
  1753.     chop($answer = <STDIN>);
  1754.  
  1755. .fi
  1756. If you chop a list, each element is chopped.
  1757. Only the value of the last chop is returned.
  1758. .Ip "chown(LIST)" 8 2
  1759. .Ip "chown LIST" 8 2
  1760. Changes the owner (and group) of a list of files.
  1761. The first two elements of the list must be the NUMERICAL uid and gid,
  1762. in that order.
  1763. Returns the number of files successfully changed.
  1764. .nf
  1765.  
  1766. .ne 2
  1767.     $cnt = chown $uid, $gid, \'foo\', \'bar\';
  1768.     chown $uid, $gid, @filenames;
  1769.  
  1770. .fi
  1771. .ne 23
  1772. Here's an example that looks up non-numeric uids in the passwd file:
  1773. .nf
  1774.  
  1775.     print "User: ";
  1776.     $user = <STDIN>;
  1777.     chop($user);
  1778.     print "Files: "
  1779.     $pattern = <STDIN>;
  1780.     chop($pattern);
  1781. .ie t \{\
  1782.     open(pass, \'/etc/passwd\') || die "Can't open passwd: $!\en";
  1783. 'br\}
  1784. .el \{\
  1785.     open(pass, \'/etc/passwd\')
  1786.         || die "Can't open passwd: $!\en";
  1787. 'br\}
  1788.     while (<pass>) {
  1789.         ($login,$pass,$uid,$gid) = split(/:/);
  1790.         $uid{$login} = $uid;
  1791.         $gid{$login} = $gid;
  1792.     }
  1793.     @ary = <${pattern}>;    # get filenames
  1794.     if ($uid{$user} eq \'\') {
  1795.         die "$user not in passwd file";
  1796.     }
  1797.     else {
  1798.         chown $uid{$user}, $gid{$user}, @ary;
  1799.     }
  1800.  
  1801. .fi
  1802. .Ip "chroot(FILENAME)" 8 5
  1803. .Ip "chroot FILENAME" 8
  1804. Does the same as the system call of that name.
  1805. If you don't know what it does, don't worry about it.
  1806. If FILENAME is omitted, does chroot to $_.
  1807. .Ip "close(FILEHANDLE)" 8 5
  1808. .Ip "close FILEHANDLE" 8
  1809. Closes the file or pipe associated with the file handle.
  1810. You don't have to close FILEHANDLE if you are immediately going to
  1811. do another open on it, since open will close it for you.
  1812. (See
  1813. .IR open .)
  1814. However, an explicit close on an input file resets the line counter ($.), while
  1815. the implicit close done by
  1816. .I open
  1817. does not.
  1818. Also, closing a pipe will wait for the process executing on the pipe to complete,
  1819. in case you want to look at the output of the pipe afterwards.
  1820. Closing a pipe explicitly also puts the status value of the command into $?.
  1821. Example:
  1822. .nf
  1823.  
  1824. .ne 4
  1825.     open(OUTPUT, \'|sort >foo\');    # pipe to sort
  1826.     .\|.\|.    # print stuff to output
  1827.     close OUTPUT;        # wait for sort to finish
  1828.     open(INPUT, \'foo\');    # get sort's results
  1829.  
  1830. .fi
  1831. FILEHANDLE may be an expression whose value gives the real filehandle name.
  1832. .Ip "closedir(DIRHANDLE)" 8 5
  1833. .Ip "closedir DIRHANDLE" 8
  1834. Closes a directory opened by opendir().
  1835. .Ip "connect(SOCKET,NAME)" 8 2
  1836. Does the same thing that the connect system call does.
  1837. Returns true if it succeeded, false otherwise.
  1838. NAME should be a package address of the proper type for the socket.
  1839. See example in section on Interprocess Communication.
  1840. .Ip "cos(EXPR)" 8 6
  1841. .Ip "cos EXPR" 8 6
  1842. Returns the cosine of EXPR (expressed in radians).
  1843. If EXPR is omitted takes cosine of $_.
  1844. .Ip "crypt(PLAINTEXT,SALT)" 8 6
  1845. Encrypts a string exactly like the crypt() function in the C library.
  1846. Useful for checking the password file for lousy passwords.
  1847. Only the guys wearing white hats should do this.
  1848. .Ip "dbmclose(ASSOC_ARRAY)" 8 6
  1849. .Ip "dbmclose ASSOC_ARRAY" 8
  1850. Breaks the binding between a dbm file and an associative array.
  1851. The values remaining in the associative array are meaningless unless
  1852. you happen to want to know what was in the cache for the dbm file.
  1853. This function is only useful if you have ndbm.
  1854. .Ip "dbmopen(ASSOC,DBNAME,MODE)" 8 6
  1855. This binds a dbm or ndbm file to an associative array.
  1856. ASSOC is the name of the associative array.
  1857. (Unlike normal open, the first argument is NOT a filehandle, even though
  1858. it looks like one).
  1859. DBNAME is the name of the database (without the .dir or .pag extension).
  1860. If the database does not exist, it is created with protection specified
  1861. by MODE (as modified by the umask).
  1862. If your system only supports the older dbm functions, you may perform only one
  1863. dbmopen in your program.
  1864. If your system has neither dbm nor ndbm, calling dbmopen produces a fatal
  1865. error.
  1866. .Sp
  1867. Values assigned to the associative array prior to the dbmopen are lost.
  1868. A certain number of values from the dbm file are cached in memory.
  1869. By default this number is 64, but you can increase it by preallocating
  1870. that number of garbage entries in the associative array before the dbmopen.
  1871. You can flush the cache if necessary with the reset command.
  1872. .Sp
  1873. If you don't have write access to the dbm file, you can only read
  1874. associative array variables, not set them.
  1875. If you want to test whether you can write, either use file tests or
  1876. try setting a dummy array entry inside an eval, which will trap the error.
  1877. .Sp
  1878. Note that functions such as keys() and values() may return huge array values
  1879. when used on large dbm files.
  1880. You may prefer to use the each() function to iterate over large dbm files.
  1881. Example:
  1882. .nf
  1883.  
  1884. .ne 6
  1885.     # print out history file offsets
  1886.     dbmopen(HIST,'/usr/lib/news/history',0666);
  1887.     while (($key,$val) = each %HIST) {
  1888.         print $key, ' = ', unpack('L',$val), "\en";
  1889.     }
  1890.     dbmclose(HIST);
  1891.  
  1892. .fi
  1893. .Ip "defined(EXPR)" 8 6
  1894. .Ip "defined EXPR" 8
  1895. Returns a boolean value saying whether the lvalue EXPR has a real value
  1896. or not.
  1897. Many operations return the undefined value under exceptional conditions,
  1898. such as end of file, uninitialized variable, system error and such.
  1899. This function allows you to distinguish between an undefined null string
  1900. and a defined null string with operations that might return a real null
  1901. string, in particular referencing elements of an array.
  1902. You may also check to see if arrays or subroutines exist.
  1903. Use on predefined variables is not guaranteed to produce intuitive results.
  1904. Examples:
  1905. .nf
  1906.  
  1907. .ne 7
  1908.     print if defined $switch{'D'};
  1909.     print "$val\en" while defined($val = pop(@ary));
  1910.     die "Can't readlink $sym: $!"
  1911.         unless defined($value = readlink $sym);
  1912.     eval '@foo = ()' if defined(@foo);
  1913.     die "No XYZ package defined" unless defined %_XYZ;
  1914.     sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }
  1915.  
  1916. .fi
  1917. See also undef.
  1918. .Ip "delete $ASSOC{KEY}" 8 6
  1919. Deletes the specified value from the specified associative array.
  1920. Returns the deleted value, or the undefined value if nothing was deleted.
  1921. Deleting from $ENV{} modifies the environment.
  1922. Deleting from an array bound to a dbm file deletes the entry from the dbm
  1923. file.
  1924. .Sp
  1925. The following deletes all the values of an associative array:
  1926. .nf
  1927.  
  1928. .ne 3
  1929.     foreach $key (keys %ARRAY) {
  1930.         delete $ARRAY{$key};
  1931.     }
  1932.  
  1933. .fi
  1934. (But it would be faster to use the
  1935. .I reset
  1936. command.
  1937. Saying undef %ARRAY is faster yet.)
  1938. .Ip "die(LIST)" 8
  1939. .Ip "die LIST" 8
  1940. Outside of an eval, prints the value of LIST to
  1941. .I STDERR
  1942. and exits with the current value of $!
  1943. (errno).
  1944. If $! is 0, exits with the value of ($? >> 8) (\`command\` status).
  1945. If ($? >> 8) is 0, exits with 255.
  1946. Inside an eval, the error message is stuffed into $@ and the eval is terminated
  1947. with the undefined value.
  1948. .Sp
  1949. Equivalent examples:
  1950. .nf
  1951.  
  1952. .ne 3
  1953. .ie t \{\
  1954.     die "Can't cd to spool: $!\en" unless chdir \'/usr/spool/news\';
  1955. 'br\}
  1956. .el \{\
  1957.     die "Can't cd to spool: $!\en"
  1958.         unless chdir \'/usr/spool/news\';
  1959. 'br\}
  1960.  
  1961.     chdir \'/usr/spool/news\' || die "Can't cd to spool: $!\en" 
  1962.  
  1963. .fi
  1964. .Sp
  1965. If the value of EXPR does not end in a newline, the current script line
  1966. number and input line number (if any) are also printed, and a newline is
  1967. supplied.
  1968. Hint: sometimes appending \*(L", stopped\*(R" to your message will cause it to make
  1969. better sense when the string \*(L"at foo line 123\*(R" is appended.
  1970. Suppose you are running script \*(L"canasta\*(R".
  1971. .nf
  1972.  
  1973. .ne 7
  1974.     die "/etc/games is no good";
  1975.     die "/etc/games is no good, stopped";
  1976.  
  1977. produce, respectively
  1978.  
  1979.     /etc/games is no good at canasta line 123.
  1980.     /etc/games is no good, stopped at canasta line 123.
  1981.  
  1982. .fi
  1983. See also
  1984. .IR exit .
  1985. .Ip "do BLOCK" 8 4
  1986. Returns the value of the last command in the sequence of commands indicated
  1987. by BLOCK.
  1988. When modified by a loop modifier, executes the BLOCK once before testing the
  1989. loop condition.
  1990. (On other statements the loop modifiers test the conditional first.)
  1991. .Ip "do SUBROUTINE (LIST)" 8 3
  1992. Executes a SUBROUTINE declared by a
  1993. .I sub
  1994. declaration, and returns the value
  1995. of the last expression evaluated in SUBROUTINE.
  1996. If there is no subroutine by that name, produces a fatal error.
  1997. (You may use the \*(L"defined\*(R" operator to determine if a subroutine
  1998. exists.)
  1999. If you pass arrays as part of LIST you may wish to pass the length
  2000. of the array in front of each array.
  2001. (See the section on subroutines later on.)
  2002. The parentheses are required to avoid confusion with the \*(L"do EXPR\*(R"
  2003. form.
  2004. .Sp
  2005. SUBROUTINE may also be a single scalar variable, in which case
  2006. the name of the subroutine to execute is taken from the variable.
  2007. .Sp
  2008. As an alternate (and preferred) form,
  2009. you may call a subroutine by prefixing the name with
  2010. an ampersand: &foo(@args).
  2011. If you aren't passing any arguments, you don't have to use parentheses.
  2012. If you omit the parentheses, no @_ array is passed to the subroutine.
  2013. The & form is also used to specify subroutines to the defined and undef
  2014. operators:
  2015. .nf
  2016.  
  2017.     if (defined &$var) { &$var($parm); undef &$var; }
  2018.  
  2019. .fi
  2020. .Ip "do EXPR" 8 3
  2021. Uses the value of EXPR as a filename and executes the contents of the file
  2022. as a
  2023. .I perl
  2024. script.
  2025. Its primary use is to include subroutines from a
  2026. .I perl
  2027. subroutine library.
  2028. .nf
  2029.  
  2030.     do \'stat.pl\';
  2031.  
  2032. is just like
  2033.  
  2034.     eval \`cat stat.pl\`;
  2035.  
  2036. .fi
  2037. except that it's more efficient, more concise, keeps track of the current
  2038. filename for error messages, and searches all the
  2039. .B \-I
  2040. libraries if the file
  2041. isn't in the current directory (see also the @INC array in Predefined Names).
  2042. It's the same, however, in that it does reparse the file every time you
  2043. call it, so if you are going to use the file inside a loop you might prefer
  2044. to use \-P and #include, at the expense of a little more startup time.
  2045. (The main problem with #include is that cpp doesn't grok # comments\*(--a
  2046. workaround is to use \*(L";#\*(R" for standalone comments.)
  2047. Note that the following are NOT equivalent:
  2048. .nf
  2049.  
  2050. .ne 2
  2051.     do $foo;    # eval a file
  2052.     do $foo();    # call a subroutine
  2053.  
  2054. .fi
  2055. Note that inclusion of library routines is better done with
  2056. the \*(L"require\*(R" operator.
  2057. .Ip "dump LABEL" 8 6
  2058. This causes an immediate core dump.
  2059. Primarily this is so that you can use the undump program to turn your
  2060. core dump into an executable binary after having initialized all your
  2061. variables at the beginning of the program.
  2062. When the new binary is executed it will begin by executing a "goto LABEL"
  2063. (with all the restrictions that goto suffers).
  2064. Think of it as a goto with an intervening core dump and reincarnation.
  2065. If LABEL is omitted, restarts the program from the top.
  2066. WARNING: any files opened at the time of the dump will NOT be open any more
  2067. when the program is reincarnated, with possible resulting confusion on the part
  2068. of perl.
  2069. See also \-u.
  2070. .Sp
  2071. Example:
  2072. .nf
  2073.  
  2074. .ne 16
  2075.     #!/usr/bin/perl
  2076.     require 'getopt.pl';
  2077.     require 'stat.pl';
  2078.     %days = (
  2079.         'Sun',1,
  2080.         'Mon',2,
  2081.         'Tue',3,
  2082.         'Wed',4,
  2083.         'Thu',5,
  2084.         'Fri',6,
  2085.         'Sat',7);
  2086.  
  2087.     dump QUICKSTART if $ARGV[0] eq '-d';
  2088.  
  2089.     QUICKSTART:
  2090.     do Getopt('f');
  2091.  
  2092. .fi
  2093. .Ip "each(ASSOC_ARRAY)" 8 6
  2094. .Ip "each ASSOC_ARRAY" 8
  2095. Returns a 2 element array consisting of the key and value for the next
  2096. value of an associative array, so that you can iterate over it.
  2097. Entries are returned in an apparently random order.
  2098. When the array is entirely read, a null array is returned (which when
  2099. assigned produces a FALSE (0) value).
  2100. The next call to each() after that will start iterating again.
  2101. The iterator can be reset only by reading all the elements from the array.
  2102. You must not modify the array while iterating over it.
  2103. There is a single iterator for each associative array, shared by all
  2104. each(), keys() and values() function calls in the program.
  2105. The following prints out your environment like the printenv program, only
  2106. in a different order:
  2107. .nf
  2108.  
  2109. .ne 3
  2110.     while (($key,$value) = each %ENV) {
  2111.         print "$key=$value\en";
  2112.     }
  2113.  
  2114. .fi
  2115. See also keys() and values().
  2116. .Ip "eof(FILEHANDLE)" 8 8
  2117. .Ip "eof()" 8
  2118. .Ip "eof" 8
  2119. Returns 1 if the next read on FILEHANDLE will return end of file, or if
  2120. FILEHANDLE is not open.
  2121. FILEHANDLE may be an expression whose value gives the real filehandle name.
  2122. (Note that this function actually reads a character and then ungetc's it,
  2123. so it is not very useful in an interactive context.)
  2124. An eof without an argument returns the eof status for the last file read.
  2125. Empty parentheses () may be used to indicate the pseudo file formed of the
  2126. files listed on the command line, i.e. eof() is reasonable to use inside
  2127. a while (<>) loop to detect the end of only the last file.
  2128. Use eof(ARGV) or eof without the parentheses to test EACH file in a while (<>) loop.
  2129. Examples:
  2130. .nf
  2131.  
  2132. .ne 7
  2133.     # insert dashes just before last line of last file
  2134.     while (<>) {
  2135.         if (eof()) {
  2136.             print "\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\|\-\en";
  2137.         }
  2138.         print;
  2139.     }
  2140.  
  2141. .ne 7
  2142.     # reset line numbering on each input file
  2143.     while (<>) {
  2144.         print "$.\et$_";
  2145.         if (eof) {    # Not eof().
  2146.             close(ARGV);
  2147.         }
  2148.     }
  2149.  
  2150. .fi
  2151. .Ip "eval(EXPR)" 8 6
  2152. .Ip "eval EXPR" 8 6
  2153. .Ip "eval BLOCK" 8 6
  2154. EXPR is parsed and executed as if it were a little
  2155. .I perl
  2156. program.
  2157. It is executed in the context of the current
  2158. .I perl
  2159. program, so that
  2160. any variable settings, subroutine or format definitions remain afterwards.
  2161. The value returned is the value of the last expression evaluated, just
  2162. as with subroutines.
  2163. If there is a syntax error or runtime error, or a die statement is
  2164. executed, an undefined value is returned by
  2165. eval, and $@ is set to the error message.
  2166. If there was no error, $@ is guaranteed to be a null string.
  2167. If EXPR is omitted, evaluates $_.
  2168. The final semicolon, if any, may be omitted from the expression.
  2169. .Sp
  2170. Note that, since eval traps otherwise-fatal errors, it is useful for
  2171. determining whether a particular feature
  2172. (such as dbmopen or symlink) is implemented.
  2173. It is also Perl's exception trapping mechanism, where the die operator is
  2174. used to raise exceptions.
  2175. .Sp
  2176. If the code to be executed doesn't vary, you may use
  2177. the eval-BLOCK form to trap run-time errors without incurring
  2178. the penalty of recompiling each time.
  2179. The error, if any, is still returned in $@.
  2180. Evaluating a single-quoted string (as EXPR) has the same effect, except that
  2181. the eval-EXPR form reports syntax errors at run time via $@, whereas the
  2182. eval-BLOCK form reports syntax errors at compile time.  The eval-EXPR form
  2183. is optimized to eval-BLOCK the first time it succeeds.  (Since the replacement
  2184. side of a substitution is considered a single-quoted string when you
  2185. use the e modifier, the same optimization occurs there.)  Examples:
  2186. .nf
  2187.  
  2188. .ne 11
  2189.     # make divide-by-zero non-fatal
  2190.     eval { $answer = $a / $b; }; warn $@ if $@;
  2191.  
  2192.     # optimized to same thing after first use
  2193.     eval '$answer = $a / $b'; warn $@ if $@;
  2194.  
  2195.     # a compile-time error
  2196.     eval { $answer = };
  2197.  
  2198.     # a run-time error
  2199.     eval '$answer =';    # sets $@
  2200.  
  2201. .fi
  2202. .Ip "exec(LIST)" 8 8
  2203. .Ip "exec LIST" 8 6
  2204. If there is more than one argument in LIST, or if LIST is an array with
  2205. more than one value,
  2206. calls execvp() with the arguments in LIST.
  2207. If there is only one scalar argument, the argument is checked for shell metacharacters.
  2208. If there are any, the entire argument is passed to \*(L"/bin/sh \-c\*(R" for parsing.
  2209. If there are none, the argument is split into words and passed directly to
  2210. execvp(), which is more efficient.
  2211. Note: exec (and system) do not flush your output buffer, so you may need to
  2212. set $| to avoid lost output.
  2213. Examples:
  2214. .nf
  2215.  
  2216.     exec \'/bin/echo\', \'Your arguments are: \', @ARGV;
  2217.     exec "sort $outfile | uniq";
  2218.  
  2219. .fi
  2220. .Sp
  2221. If you don't really want to execute the first argument, but want to lie
  2222. to the program you are executing about its own name, you can specify
  2223. the program you actually want to run by assigning that to a variable and
  2224. putting the name of the variable in front of the LIST without a comma.
  2225. (This always forces interpretation of the LIST as a multi-valued list, even
  2226. if there is only a single scalar in the list.)
  2227. Example:
  2228. .nf
  2229.  
  2230. .ne 2
  2231.     $shell = '/bin/csh';
  2232.     exec $shell '-sh';        # pretend it's a login shell
  2233.  
  2234. .fi
  2235. .Ip "exit(EXPR)" 8 6
  2236. .Ip "exit EXPR" 8
  2237. Evaluates EXPR and exits immediately with that value.
  2238. Example:
  2239. .nf
  2240.  
  2241. .ne 2
  2242.     $ans = <STDIN>;
  2243.     exit 0 \|if \|$ans \|=~ \|/\|^[Xx]\|/\|;
  2244.  
  2245. .fi
  2246. See also
  2247. .IR die .
  2248. If EXPR is omitted, exits with 0 status.
  2249. .Ip "exp(EXPR)" 8 3
  2250. .Ip "exp EXPR" 8
  2251. Returns
  2252. .I e
  2253. to the power of EXPR.
  2254. If EXPR is omitted, gives exp($_).
  2255. .Ip "fcntl(FILEHANDLE,FUNCTION,SCALAR)" 8 4
  2256. Implements the fcntl(2) function.
  2257. You'll probably have to say
  2258. .nf
  2259.  
  2260.     require "fcntl.ph";    # probably /usr/local/lib/perl/fcntl.ph
  2261.  
  2262. .fi
  2263. first to get the correct function definitions.
  2264. If fcntl.ph doesn't exist or doesn't have the correct definitions
  2265. you'll have to roll
  2266. your own, based on your C header files such as <sys/fcntl.h>.
  2267. (There is a perl script called h2ph that comes with the perl kit
  2268. which may help you in this.)
  2269. Argument processing and value return works just like ioctl below.
  2270. Note that fcntl will produce a fatal error if used on a machine that doesn't implement
  2271. fcntl(2).
  2272. .Ip "fileno(FILEHANDLE)" 8 4
  2273. .Ip "fileno FILEHANDLE" 8 4
  2274. Returns the file descriptor for a filehandle.
  2275. Useful for constructing bitmaps for select().
  2276. If FILEHANDLE is an expression, the value is taken as the name of
  2277. the filehandle.
  2278. .Ip "flock(FILEHANDLE,OPERATION)" 8 4
  2279. Calls flock(2) on FILEHANDLE.
  2280. See manual page for flock(2) for definition of OPERATION.
  2281. Returns true for success, false on failure.
  2282. Will produce a fatal error if used on a machine that doesn't implement
  2283. flock(2).
  2284. Here's a mailbox appender for BSD systems.
  2285. .nf
  2286.  
  2287. .ne 20
  2288.     $LOCK_SH = 1;
  2289.     $LOCK_EX = 2;
  2290.     $LOCK_NB = 4;
  2291.     $LOCK_UN = 8;
  2292.  
  2293.     sub lock {
  2294.         flock(MBOX,$LOCK_EX);
  2295.         # and, in case someone appended
  2296.         # while we were waiting...
  2297.         seek(MBOX, 0, 2);
  2298.     }
  2299.  
  2300.     sub unlock {
  2301.         flock(MBOX,$LOCK_UN);
  2302.     }
  2303.  
  2304.     open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
  2305.         || die "Can't open mailbox: $!";
  2306.  
  2307.     do lock();
  2308.     print MBOX $msg,"\en\en";
  2309.     do unlock();
  2310.  
  2311. .fi
  2312. .Ip "fork" 8 4
  2313. Does a fork() call.
  2314. Returns the child pid to the parent process and 0 to the child process.
  2315. Note: unflushed buffers remain unflushed in both processes, which means
  2316. you may need to set $| to avoid duplicate output.
  2317. .Ip "getc(FILEHANDLE)" 8 4
  2318. .Ip "getc FILEHANDLE" 8
  2319. .Ip "getc" 8
  2320. Returns the next character from the input file attached to FILEHANDLE, or
  2321. a null string at EOF.
  2322. If FILEHANDLE is omitted, reads from STDIN.
  2323. .Ip "getlogin" 8 3
  2324. Returns the current login from /etc/utmp, if any.
  2325. If null, use getpwuid.
  2326.  
  2327.     $login = getlogin || (getpwuid($<))[0] || "Somebody";
  2328.  
  2329. .Ip "getpeername(SOCKET)" 8 3
  2330. Returns the packed sockaddr address of other end of the SOCKET connection.
  2331. .nf
  2332.  
  2333. .ne 4
  2334.     # An internet sockaddr
  2335.     $sockaddr = 'S n a4 x8';
  2336.     $hersockaddr = getpeername(S);
  2337. .ie t \{\
  2338.     ($family, $port, $heraddr) = unpack($sockaddr,$hersockaddr);
  2339. 'br\}
  2340. .el \{\
  2341.     ($family, $port, $heraddr) =
  2342.             unpack($sockaddr,$hersockaddr);
  2343. 'br\}
  2344.  
  2345. .fi
  2346. .Ip "getpgrp(PID)" 8 4
  2347. .Ip "getpgrp PID" 8
  2348. Returns the current process group for the specified PID, 0 for the current
  2349. process.
  2350. Will produce a fatal error if used on a machine that doesn't implement
  2351. getpgrp(2).
  2352. If EXPR is omitted, returns process group of current process.
  2353. .Ip "getppid" 8 4
  2354. Returns the process id of the parent process.
  2355. .Ip "getpriority(WHICH,WHO)" 8 4
  2356. Returns the current priority for a process, a process group, or a user.
  2357. (See getpriority(2).)
  2358. Will produce a fatal error if used on a machine that doesn't implement
  2359. getpriority(2).
  2360. .Ip "getpwnam(NAME)" 8
  2361. .Ip "getgrnam(NAME)" 8
  2362. .Ip "gethostbyname(NAME)" 8
  2363. .Ip "getnetbyname(NAME)" 8
  2364. .Ip "getprotobyname(NAME)" 8
  2365. .Ip "getpwuid(UID)" 8
  2366. .Ip "getgrgid(GID)" 8
  2367. .Ip "getservbyname(NAME,PROTO)" 8
  2368. .Ip "gethostbyaddr(ADDR,ADDRTYPE)" 8
  2369. .Ip "getnetbyaddr(ADDR,ADDRTYPE)" 8
  2370. .Ip "getprotobynumber(NUMBER)" 8
  2371. .Ip "getservbyport(PORT,PROTO)" 8
  2372. .Ip "getpwent" 8
  2373. .Ip "getgrent" 8
  2374. .Ip "gethostent" 8
  2375. .Ip "getnetent" 8
  2376. .Ip "getprotoent" 8
  2377. .Ip "getservent" 8
  2378. .Ip "setpwent" 8
  2379. .Ip "setgrent" 8
  2380. .Ip "sethostent(STAYOPEN)" 8
  2381. .Ip "setnetent(STAYOPEN)" 8
  2382. .Ip "setprotoent(STAYOPEN)" 8
  2383. .Ip "setservent(STAYOPEN)" 8
  2384. .Ip "endpwent" 8
  2385. .Ip "endgrent" 8
  2386. .Ip "endhostent" 8
  2387. .Ip "endnetent" 8
  2388. .Ip "endprotoent" 8
  2389. .Ip "endservent" 8
  2390. These routines perform the same functions as their counterparts in the
  2391. system library.
  2392. The return values from the various get routines are as follows:
  2393. .nf
  2394.  
  2395.     ($name,$passwd,$uid,$gid,
  2396.        $quota,$comment,$gcos,$dir,$shell) = getpw.\|.\|.
  2397.     ($name,$passwd,$gid,$members) = getgr.\|.\|.
  2398.     ($name,$aliases,$addrtype,$length,@addrs) = gethost.\|.\|.
  2399.     ($name,$aliases,$addrtype,$net) = getnet.\|.\|.
  2400.     ($name,$aliases,$proto) = getproto.\|.\|.
  2401.     ($name,$aliases,$port,$proto) = getserv.\|.\|.
  2402.  
  2403. .fi
  2404. The $members value returned by getgr.\|.\|. is a space separated list
  2405. of the login names of the members of the group.
  2406. .Sp
  2407. The @addrs value returned by the gethost.\|.\|. functions is a list of the
  2408. raw addresses returned by the corresponding system library call.
  2409. In the Internet domain, each address is four bytes long and you can unpack
  2410. it by saying something like:
  2411. .nf
  2412.  
  2413.     ($a,$b,$c,$d) = unpack('C4',$addr[0]);
  2414.  
  2415. .fi
  2416. .Ip "getsockname(SOCKET)" 8 3
  2417. Returns the packed sockaddr address of this end of the SOCKET connection.
  2418. .nf
  2419.  
  2420. .ne 4
  2421.     # An internet sockaddr
  2422.     $sockaddr = 'S n a4 x8';
  2423.     $mysockaddr = getsockname(S);
  2424. .ie t \{\
  2425.     ($family, $port, $myaddr) = unpack($sockaddr,$mysockaddr);
  2426. 'br\}
  2427. .el \{\
  2428.     ($family, $port, $myaddr) =
  2429.             unpack($sockaddr,$mysockaddr);
  2430. 'br\}
  2431.  
  2432. .fi
  2433. .Ip "getsockopt(SOCKET,LEVEL,OPTNAME)" 8 3
  2434. Returns the socket option requested, or undefined if there is an error.
  2435. .Ip "gmtime(EXPR)" 8 4
  2436. .Ip "gmtime EXPR" 8
  2437. Converts a time as returned by the time function to a 9-element array with
  2438. the time analyzed for the Greenwich timezone.
  2439. Typically used as follows:
  2440. .nf
  2441.  
  2442. .ne 3
  2443. .ie t \{\
  2444.     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);
  2445. 'br\}
  2446. .el \{\
  2447.     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  2448.                         gmtime(time);
  2449. 'br\}
  2450.  
  2451. .fi
  2452. All array elements are numeric, and come straight out of a struct tm.
  2453. In particular this means that $mon has the range 0.\|.11 and $wday has the
  2454. range 0.\|.6.
  2455. If EXPR is omitted, does gmtime(time).
  2456. .Ip "goto LABEL" 8 6
  2457. Finds the statement labeled with LABEL and resumes execution there.
  2458. Currently you may only go to statements in the main body of the program
  2459. that are not nested inside a do {} construct.
  2460. This statement is not implemented very efficiently, and is here only to make
  2461. the
  2462. .IR sed -to- perl
  2463. translator easier.
  2464. I may change its semantics at any time, consistent with support for translated
  2465. .I sed
  2466. scripts.
  2467. Use it at your own risk.
  2468. Better yet, don't use it at all.
  2469. .Ip "grep(EXPR,LIST)" 8 4
  2470. Evaluates EXPR for each element of LIST (locally setting $_ to each element)
  2471. and returns the array value consisting of those elements for which the
  2472. expression evaluated to true.
  2473. In a scalar context, returns the number of times the expression was true.
  2474. .nf
  2475.  
  2476.     @foo = grep(!/^#/, @bar);    # weed out comments
  2477.  
  2478. .fi
  2479. Note that, since $_ is a reference into the array value, it can be
  2480. used to modify the elements of the array.
  2481. While this is useful and supported, it can cause bizarre results if
  2482. the LIST is not a named array.
  2483. .Ip "hex(EXPR)" 8 4
  2484. .Ip "hex EXPR" 8
  2485. Returns the decimal value of EXPR interpreted as an hex string.
  2486. (To interpret strings that might start with 0 or 0x see oct().)
  2487. If EXPR is omitted, uses $_.
  2488. .Ip "index(STR,SUBSTR,POSITION)" 8 4
  2489. .Ip "index(STR,SUBSTR)" 8 4
  2490. Returns the position of the first occurrence of SUBSTR in STR at or after
  2491. POSITION.
  2492. If POSITION is omitted, starts searching from the beginning of the string.
  2493. The return value is based at 0, or whatever you've
  2494. set the $[ variable to.
  2495. If the substring is not found, returns one less than the base, ordinarily \-1.
  2496. .Ip "int(EXPR)" 8 4
  2497. .Ip "int EXPR" 8
  2498. Returns the integer portion of EXPR.
  2499. If EXPR is omitted, uses $_.
  2500. .Ip "ioctl(FILEHANDLE,FUNCTION,SCALAR)" 8 4
  2501. Implements the ioctl(2) function.
  2502. You'll probably have to say
  2503. .nf
  2504.  
  2505.     require "ioctl.ph";    # probably /usr/local/lib/perl/ioctl.ph
  2506.  
  2507. .fi
  2508. first to get the correct function definitions.
  2509. If ioctl.ph doesn't exist or doesn't have the correct definitions
  2510. you'll have to roll
  2511. your own, based on your C header files such as <sys/ioctl.h>.
  2512. (There is a perl script called h2ph that comes with the perl kit
  2513. which may help you in this.)
  2514. SCALAR will be read and/or written depending on the FUNCTION\*(--a pointer
  2515. to the string value of SCALAR will be passed as the third argument of
  2516. the actual ioctl call.
  2517. (If SCALAR has no string value but does have a numeric value, that value
  2518. will be passed rather than a pointer to the string value.
  2519. To guarantee this to be true, add a 0 to the scalar before using it.)
  2520. The pack() and unpack() functions are useful for manipulating the values
  2521. of structures used by ioctl().
  2522. The following example sets the erase character to DEL.
  2523. .nf
  2524.  
  2525. .ne 9
  2526.     require 'ioctl.ph';
  2527.     $sgttyb_t = "ccccs";        # 4 chars and a short
  2528.     if (ioctl(STDIN,$TIOCGETP,$sgttyb)) {
  2529.         @ary = unpack($sgttyb_t,$sgttyb);
  2530.         $ary[2] = 127;
  2531.         $sgttyb = pack($sgttyb_t,@ary);
  2532.         ioctl(STDIN,$TIOCSETP,$sgttyb)
  2533.             || die "Can't ioctl: $!";
  2534.     }
  2535.  
  2536. .fi
  2537. The return value of ioctl (and fcntl) is as follows:
  2538. .nf
  2539.  
  2540. .ne 4
  2541.     if OS returns:\h'|3i'perl returns:
  2542.       -1\h'|3i'  undefined value
  2543.       0\h'|3i'  string "0 but true"
  2544.       anything else\h'|3i'  that number
  2545.  
  2546. .fi
  2547. Thus perl returns true on success and false on failure, yet you can still
  2548. easily determine the actual value returned by the operating system:
  2549. .nf
  2550.  
  2551.     ($retval = ioctl(...)) || ($retval = -1);
  2552.     printf "System returned %d\en", $retval;
  2553. .fi
  2554. .Ip "join(EXPR,LIST)" 8 8
  2555. .Ip "join(EXPR,ARRAY)" 8
  2556. Joins the separate strings of LIST or ARRAY into a single string with fields
  2557. separated by the value of EXPR, and returns the string.
  2558. Example:
  2559. .nf
  2560.     
  2561. .ie t \{\
  2562.     $_ = join(\|\':\', $login,$passwd,$uid,$gid,$gcos,$home,$shell);
  2563. 'br\}
  2564. .el \{\
  2565.     $_ = join(\|\':\',
  2566.         $login,$passwd,$uid,$gid,$gcos,$home,$shell);
  2567. 'br\}
  2568.  
  2569. .fi
  2570. See
  2571. .IR split .
  2572. .Ip "keys(ASSOC_ARRAY)" 8 6
  2573. .Ip "keys ASSOC_ARRAY" 8
  2574. Returns a normal array consisting of all the keys of the named associative
  2575. array.
  2576. The keys are returned in an apparently random order, but it is the same order
  2577. as either the values() or each() function produces (given that the associative array
  2578. has not been modified).
  2579. Here is yet another way to print your environment:
  2580. .nf
  2581.  
  2582. .ne 5
  2583.     @keys = keys %ENV;
  2584.     @values = values %ENV;
  2585.     while ($#keys >= 0) {
  2586.         print pop(@keys), \'=\', pop(@values), "\en";
  2587.     }
  2588.  
  2589. or how about sorted by key:
  2590.  
  2591. .ne 3
  2592.     foreach $key (sort(keys %ENV)) {
  2593.         print $key, \'=\', $ENV{$key}, "\en";
  2594.     }
  2595.  
  2596. .fi
  2597. .Ip "kill(LIST)" 8 8
  2598. .Ip "kill LIST" 8 2
  2599. Sends a signal to a list of processes.
  2600. The first element of the list must be the signal to send.
  2601. Returns the number of processes successfully signaled.
  2602. .nf
  2603.  
  2604.     $cnt = kill 1, $child1, $child2;
  2605.     kill 9, @goners;
  2606.  
  2607. .fi
  2608. If the signal is negative, kills process groups instead of processes.
  2609. (On System V, a negative \fIprocess\fR number will also kill process groups,
  2610. but that's not portable.)
  2611. You may use a signal name in quotes.
  2612. .Ip "last LABEL" 8 8
  2613. .Ip "last" 8
  2614. The
  2615. .I last
  2616. command is like the
  2617. .I break
  2618. statement in C (as used in loops); it immediately exits the loop in question.
  2619. If the LABEL is omitted, the command refers to the innermost enclosing loop.
  2620. The
  2621. .I continue
  2622. block, if any, is not executed:
  2623. .nf
  2624.  
  2625. .ne 4
  2626.     line: while (<STDIN>) {
  2627.         last line if /\|^$/;    # exit when done with header
  2628.         .\|.\|.
  2629.     }
  2630.  
  2631. .fi
  2632. .Ip "length(EXPR)" 8 4
  2633. .Ip "length EXPR" 8
  2634. Returns the length in characters of the value of EXPR.
  2635. If EXPR is omitted, returns length of $_.
  2636. .Ip "link(OLDFILE,NEWFILE)" 8 2
  2637. Creates a new filename linked to the old filename.
  2638. Returns 1 for success, 0 otherwise.
  2639. .Ip "listen(SOCKET,QUEUESIZE)" 8 2
  2640. Does the same thing that the listen system call does.
  2641. Returns true if it succeeded, false otherwise.
  2642. See example in section on Interprocess Communication.
  2643. .Ip "local(LIST)" 8 4
  2644. Declares the listed variables to be local to the enclosing block,
  2645. subroutine, eval or \*(L"do\*(R".
  2646. All the listed elements must be legal lvalues.
  2647. This operator works by saving the current values of those variables in LIST
  2648. on a hidden stack and restoring them upon exiting the block, subroutine or eval.
  2649. This means that called subroutines can also reference the local variable,
  2650. but not the global one.
  2651. The LIST may be assigned to if desired, which allows you to initialize
  2652. your local variables.
  2653. (If no initializer is given for a particular variable, it is created with
  2654. an undefined value.)
  2655. Commonly this is used to name the parameters to a subroutine.
  2656. Examples:
  2657. .nf
  2658.  
  2659. .ne 13
  2660.     sub RANGEVAL {
  2661.         local($min, $max, $thunk) = @_;
  2662.         local($result) = \'\';
  2663.         local($i);
  2664.  
  2665.         # Presumably $thunk makes reference to $i
  2666.  
  2667.         for ($i = $min; $i < $max; $i++) {
  2668.             $result .= eval $thunk;
  2669.         }
  2670.  
  2671.         $result;
  2672.     }
  2673.  
  2674. .ne 6
  2675.     if ($sw eq \'-v\') {
  2676.         # init local array with global array
  2677.         local(@ARGV) = @ARGV;
  2678.         unshift(@ARGV,\'echo\');
  2679.         system @ARGV;
  2680.     }
  2681.     # @ARGV restored
  2682.  
  2683. .ne 6
  2684.     # temporarily add to digits associative array
  2685.     if ($base12) {
  2686.         # (NOTE: not claiming this is efficient!)
  2687.         local(%digits) = (%digits,'t',10,'e',11);
  2688.         do parse_num();
  2689.     }
  2690.  
  2691. .fi
  2692. Note that local() is a run-time command, and so gets executed every time
  2693. through a loop, using up more stack storage each time until it's all
  2694. released at once when the loop is exited.
  2695. .Ip "localtime(EXPR)" 8 4
  2696. .Ip "localtime EXPR" 8
  2697. Converts a time as returned by the time function to a 9-element array with
  2698. the time analyzed for the local timezone.
  2699. Typically used as follows:
  2700. .nf
  2701.  
  2702. .ne 3
  2703. .ie t \{\
  2704.     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
  2705. 'br\}
  2706. .el \{\
  2707.     ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  2708.                         localtime(time);
  2709. 'br\}
  2710.  
  2711. .fi
  2712. All array elements are numeric, and come straight out of a struct tm.
  2713. In particular this means that $mon has the range 0.\|.11 and $wday has the
  2714. range 0.\|.6.
  2715. If EXPR is omitted, does localtime(time).
  2716. .Ip "log(EXPR)" 8 4
  2717. .Ip "log EXPR" 8
  2718. Returns logarithm (base
  2719. .IR e )
  2720. of EXPR.
  2721. If EXPR is omitted, returns log of $_.
  2722. .Ip "lstat(FILEHANDLE)" 8 6
  2723. .Ip "lstat FILEHANDLE" 8
  2724. .Ip "lstat(EXPR)" 8
  2725. .Ip "lstat SCALARVARIABLE" 8
  2726. Does the same thing as the stat() function, but stats a symbolic link
  2727. instead of the file the symbolic link points to.
  2728. If symbolic links are unimplemented on your system, a normal stat is done.
  2729. .Ip "m/PATTERN/gio" 8 4
  2730. .Ip "/PATTERN/gio" 8
  2731. Searches a string for a pattern match, and returns true (1) or false (\'\').
  2732. If no string is specified via the =~ or !~ operator,
  2733. the $_ string is searched.
  2734. (The string specified with =~ need not be an lvalue\*(--it may be the result of an expression evaluation, but remember the =~ binds rather tightly.)
  2735. See also the section on regular expressions.
  2736. .Sp
  2737. If / is the delimiter then the initial \*(L'm\*(R' is optional.
  2738. With the \*(L'm\*(R' you can use any pair of non-alphanumeric characters
  2739. as delimiters.
  2740. This is particularly useful for matching Unix path names that contain \*(L'/\*(R'.
  2741. If the final delimiter is followed by the optional letter \*(L'i\*(R', the matching is
  2742. done in a case-insensitive manner.
  2743. PATTERN may contain references to scalar variables, which will be interpolated
  2744. (and the pattern recompiled) every time the pattern search is evaluated.
  2745. (Note that $) and $| may not be interpolated because they look like end-of-string tests.)
  2746. If you want such a pattern to be compiled only once, add an \*(L"o\*(R" after
  2747. the trailing delimiter.
  2748. This avoids expensive run-time recompilations, and
  2749. is useful when the value you are interpolating won't change over the
  2750. life of the script.
  2751. If the PATTERN evaluates to a null string, the most recent successful
  2752. regular expression is used instead.
  2753. .Sp
  2754. If used in a context that requires an array value, a pattern match returns an
  2755. array consisting of the subexpressions matched by the parentheses in the
  2756. pattern,
  2757. i.e. ($1, $2, $3.\|.\|.).
  2758. It does NOT actually set $1, $2, etc. in this case, nor does it set $+, $`, $&
  2759. or $'.
  2760. If the match fails, a null array is returned.
  2761. If the match succeeds, but there were no parentheses, an array value of (1)
  2762. is returned.
  2763. .Sp
  2764. Examples:
  2765. .nf
  2766.  
  2767. .ne 4
  2768.     open(tty, \'/dev/tty\');
  2769.     <tty> \|=~ \|/\|^y\|/i \|&& \|do foo(\|);    # do foo if desired
  2770.  
  2771.     if (/Version: \|*\|([0\-9.]*\|)\|/\|) { $version = $1; }
  2772.  
  2773.     next if m#^/usr/spool/uucp#;
  2774.  
  2775. .ne 5
  2776.     # poor man's grep
  2777.     $arg = shift;
  2778.     while (<>) {
  2779.         print if /$arg/o;    # compile only once
  2780.     }
  2781.  
  2782.     if (($F1, $F2, $Etc) = ($foo =~ /^(\eS+)\es+(\eS+)\es*(.*)/))
  2783.  
  2784. .fi
  2785. This last example splits $foo into the first two words and the remainder
  2786. of the line, and assigns those three fields to $F1, $F2 and $Etc.
  2787. The conditional is true if any variables were assigned, i.e. if the pattern
  2788. matched.
  2789. .Sp
  2790. The \*(L"g\*(R" modifier specifies global pattern matching\*(--that is,
  2791. matching as many times as possible within the string.  How it behaves
  2792. depends on the context.  In an array context, it returns a list of
  2793. all the substrings matched by all the parentheses in the regular expression.
  2794. If there are no parentheses, it returns a list of all the matched strings,
  2795. as if there were parentheses around the whole pattern.  In a scalar context,
  2796. it iterates through the string, returning TRUE each time it matches, and
  2797. FALSE when it eventually runs out of matches.  (In other words, it remembers
  2798. where it left off last time and restarts the search at that point.)  It
  2799. presumes that you have not modified the string since the last match.
  2800. Modifying the string between matches may result in undefined behavior.
  2801. (You can actually get away with in-place modifications via substr()
  2802. that do not change the length of the entire string.  In general, however,
  2803. you should be using s///g for such modifications.)  Examples:
  2804. .nf
  2805.  
  2806.     # array context
  2807.     ($one,$five,$fifteen) = (\`uptime\` =~ /(\ed+\e.\ed+)/g);
  2808.  
  2809.     # scalar context
  2810.     $/ = 1; $* = 1;
  2811.     while ($paragraph = <>) {
  2812.         while ($paragraph =~ /[a-z][\'")]*[.!?]+[\'")]*\es/g) {
  2813.         $sentences++;
  2814.         }
  2815.     }
  2816.     print "$sentences\en";
  2817.  
  2818. .fi
  2819. .Ip "mkdir(FILENAME,MODE)" 8 3
  2820. Creates the directory specified by FILENAME, with permissions specified by
  2821. MODE (as modified by umask).
  2822. If it succeeds it returns 1, otherwise it returns 0 and sets $! (errno).
  2823. .Ip "msgctl(ID,CMD,ARG)" 8 4
  2824. Calls the System V IPC function msgctl.  If CMD is &IPC_STAT, then ARG
  2825. must be a variable which will hold the returned msqid_ds structure.
  2826. Returns like ioctl: the undefined value for error, "0 but true" for
  2827. zero, or the actual return value otherwise.
  2828. .Ip "msgget(KEY,FLAGS)" 8 4
  2829. Calls the System V IPC function msgget.  Returns the message queue id,
  2830. or the undefined value if there is an error.
  2831. .Ip "msgsnd(ID,MSG,FLAGS)" 8 4
  2832. Calls the System V IPC function msgsnd to send the message MSG to the
  2833. message queue ID.  MSG must begin with the long integer message type,
  2834. which may be created with pack("L", $type).  Returns true if
  2835. successful, or false if there is an error.
  2836. .Ip "msgrcv(ID,VAR,SIZE,TYPE,FLAGS)" 8 4
  2837. Calls the System V IPC function msgrcv to receive a message from
  2838. message queue ID into variable VAR with a maximum message size of
  2839. SIZE.  Note that if a message is received, the message type will be
  2840. the first thing in VAR, and the maximum length of VAR is SIZE plus the
  2841. size of the message type.  Returns true if successful, or false if
  2842. there is an error.
  2843. .Ip "next LABEL" 8 8
  2844. .Ip "next" 8
  2845. The
  2846. .I next
  2847. command is like the
  2848. .I continue
  2849. statement in C; it starts the next iteration of the loop:
  2850. .nf
  2851.  
  2852. .ne 4
  2853.     line: while (<STDIN>) {
  2854.         next line if /\|^#/;    # discard comments
  2855.         .\|.\|.
  2856.     }
  2857.  
  2858. .fi
  2859. Note that if there were a
  2860. .I continue
  2861. block on the above, it would get executed even on discarded lines.
  2862. If the LABEL is omitted, the command refers to the innermost enclosing loop.
  2863. .Ip "oct(EXPR)" 8 4
  2864. .Ip "oct EXPR" 8
  2865. Returns the decimal value of EXPR interpreted as an octal string.
  2866. (If EXPR happens to start off with 0x, interprets it as a hex string instead.)
  2867. The following will handle decimal, octal and hex in the standard notation:
  2868. .nf
  2869.  
  2870.     $val = oct($val) if $val =~ /^0/;
  2871.  
  2872. .fi
  2873. If EXPR is omitted, uses $_.
  2874. .Ip "open(FILEHANDLE,EXPR)" 8 8
  2875. .Ip "open(FILEHANDLE)" 8
  2876. .Ip "open FILEHANDLE" 8
  2877. Opens the file whose filename is given by EXPR, and associates it with
  2878. FILEHANDLE.
  2879. If FILEHANDLE is an expression, its value is used as the name of the
  2880. real filehandle wanted.
  2881. If EXPR is omitted, the scalar variable of the same name as the FILEHANDLE
  2882. contains the filename.
  2883. If the filename begins with \*(L"<\*(R" or nothing, the file is opened for
  2884. input.
  2885. If the filename begins with \*(L">\*(R", the file is opened for output.
  2886. If the filename begins with \*(L">>\*(R", the file is opened for appending.
  2887. (You can put a \'+\' in front of the \'>\' or \'<\' to indicate that you
  2888. want both read and write access to the file.)
  2889. If the filename begins with \*(L"|\*(R", the filename is interpreted
  2890. as a command to which output is to be piped, and if the filename ends
  2891. with a \*(L"|\*(R", the filename is interpreted as command which pipes
  2892. input to us.
  2893. (You may not have a command that pipes both in and out.)
  2894. Opening \'\-\' opens
  2895. .I STDIN
  2896. and opening \'>\-\' opens
  2897. .IR STDOUT .
  2898. Open returns non-zero upon success, the undefined value otherwise.
  2899. If the open involved a pipe, the return value happens to be the pid
  2900. of the subprocess.
  2901. Examples:
  2902. .nf
  2903.     
  2904. .ne 3
  2905.     $article = 100;
  2906.     open article || die "Can't find article $article: $!\en";
  2907.     while (<article>) {\|.\|.\|.
  2908.  
  2909. .ie t \{\
  2910.     open(LOG, \'>>/usr/spool/news/twitlog\'\|);    # (log is reserved)
  2911. 'br\}
  2912. .el \{\
  2913.     open(LOG, \'>>/usr/spool/news/twitlog\'\|);
  2914.                     # (log is reserved)
  2915. 'br\}
  2916.  
  2917. .ie t \{\
  2918.     open(article, "caesar <$article |"\|);        # decrypt article
  2919. 'br\}
  2920. .el \{\
  2921.     open(article, "caesar <$article |"\|);
  2922.                     # decrypt article
  2923. 'br\}
  2924.  
  2925. .ie t \{\
  2926.     open(extract, "|sort >/tmp/Tmp$$"\|);        # $$ is our process#
  2927. 'br\}
  2928. .el \{\
  2929.     open(extract, "|sort >/tmp/Tmp$$"\|);
  2930.                     # $$ is our process#
  2931. 'br\}
  2932.  
  2933. .ne 7
  2934.     # process argument list of files along with any includes
  2935.  
  2936.     foreach $file (@ARGV) {
  2937.         do process($file, \'fh00\');    # no pun intended
  2938.     }
  2939.  
  2940.     sub process {
  2941.         local($filename, $input) = @_;
  2942.         $input++;        # this is a string increment
  2943.         unless (open($input, $filename)) {
  2944.             print STDERR "Can't open $filename: $!\en";
  2945.             return;
  2946.         }
  2947. .ie t \{\
  2948.         while (<$input>) {        # note the use of indirection
  2949. 'br\}
  2950. .el \{\
  2951.         while (<$input>) {        # note use of indirection
  2952. 'br\}
  2953.             if (/^#include "(.*)"/) {
  2954.                 do process($1, $input);
  2955.                 next;
  2956.             }
  2957.             .\|.\|.        # whatever
  2958.         }
  2959.     }
  2960.  
  2961. .fi
  2962. You may also, in the Bourne shell tradition, specify an EXPR beginning
  2963. with \*(L">&\*(R", in which case the rest of the string
  2964. is interpreted as the name of a filehandle
  2965. (or file descriptor, if numeric) which is to be duped and opened.
  2966. You may use & after >, >>, <, +>, +>> and +<.
  2967. The mode you specify should match the mode of the original filehandle.
  2968. Here is a script that saves, redirects, and restores
  2969. .I STDOUT
  2970. and
  2971. .IR STDERR :
  2972. .nf
  2973.  
  2974. .ne 21
  2975.     #!/usr/bin/perl
  2976.     open(SAVEOUT, ">&STDOUT");
  2977.     open(SAVEERR, ">&STDERR");
  2978.  
  2979.     open(STDOUT, ">foo.out") || die "Can't redirect stdout";
  2980.     open(STDERR, ">&STDOUT") || die "Can't dup stdout";
  2981.  
  2982.     select(STDERR); $| = 1;        # make unbuffered
  2983.     select(STDOUT); $| = 1;        # make unbuffered
  2984.  
  2985.     print STDOUT "stdout 1\en";    # this works for
  2986.     print STDERR "stderr 1\en";     # subprocesses too
  2987.  
  2988.     close(STDOUT);
  2989.     close(STDERR);
  2990.  
  2991.     open(STDOUT, ">&SAVEOUT");
  2992.     open(STDERR, ">&SAVEERR");
  2993.  
  2994.     print STDOUT "stdout 2\en";
  2995.     print STDERR "stderr 2\en";
  2996.  
  2997. .fi
  2998. If you open a pipe on the command \*(L"\-\*(R", i.e. either \*(L"|\-\*(R" or \*(L"\-|\*(R",
  2999. then there is an implicit fork done, and the return value of open
  3000. is the pid of the child within the parent process, and 0 within the child
  3001. process.
  3002. (Use defined($pid) to determine if the open was successful.)
  3003. The filehandle behaves normally for the parent, but i/o to that
  3004. filehandle is piped from/to the
  3005. .IR STDOUT / STDIN
  3006. of the child process.
  3007. In the child process the filehandle isn't opened\*(--i/o happens from/to
  3008. the new
  3009. .I STDOUT
  3010. or
  3011. .IR STDIN .
  3012. Typically this is used like the normal piped open when you want to exercise
  3013. more control over just how the pipe command gets executed, such as when
  3014. you are running setuid, and don't want to have to scan shell commands
  3015. for metacharacters.
  3016. The following pairs are more or less equivalent:
  3017. .nf
  3018.  
  3019. .ne 5
  3020.     open(FOO, "|tr \'[a\-z]\' \'[A\-Z]\'");
  3021.     open(FOO, "|\-") || exec \'tr\', \'[a\-z]\', \'[A\-Z]\';
  3022.  
  3023.     open(FOO, "cat \-n '$file'|");
  3024.     open(FOO, "\-|") || exec \'cat\', \'\-n\', $file;
  3025.  
  3026. .fi
  3027. Explicitly closing any piped filehandle causes the parent process to wait for the
  3028. child to finish, and returns the status value in $?.
  3029. Note: on any operation which may do a fork,
  3030. unflushed buffers remain unflushed in both
  3031. processes, which means you may need to set $| to
  3032. avoid duplicate output.
  3033. .Sp
  3034. The filename that is passed to open will have leading and trailing
  3035. whitespace deleted.
  3036. In order to open a file with arbitrary weird characters in it, it's necessary
  3037. to protect any leading and trailing whitespace thusly:
  3038. .nf
  3039.  
  3040. .ne 2
  3041.         $file =~ s#^(\es)#./$1#;
  3042.         open(FOO, "< $file\e0");
  3043.  
  3044. .fi
  3045. .Ip "opendir(DIRHANDLE,EXPR)" 8 3
  3046. Opens a directory named EXPR for processing by readdir(), telldir(), seekdir(),
  3047. rewinddir() and closedir().
  3048. Returns true if successful.
  3049. DIRHANDLEs have their own namespace separate from FILEHANDLEs.
  3050. .Ip "ord(EXPR)" 8 4
  3051. .Ip "ord EXPR" 8
  3052. Returns the numeric ascii value of the first character of EXPR.
  3053. If EXPR is omitted, uses $_.
  3054. ''' Comments on f & d by gnb@melba.bby.oz.au    22/11/89
  3055. .Ip "pack(TEMPLATE,LIST)" 8 4
  3056. Takes an array or list of values and packs it into a binary structure,
  3057. returning the string containing the structure.
  3058. The TEMPLATE is a sequence of characters that give the order and type
  3059. of values, as follows:
  3060. .nf
  3061.  
  3062.     A    An ascii string, will be space padded.
  3063.     a    An ascii string, will be null padded.
  3064.     c    A signed char value.
  3065.     C    An unsigned char value.
  3066.     s    A signed short value.
  3067.     S    An unsigned short value.
  3068.     i    A signed integer value.
  3069.     I    An unsigned integer value.
  3070.     l    A signed long value.
  3071.     L    An unsigned long value.
  3072.     n    A short in \*(L"network\*(R" order.
  3073.     N    A long in \*(L"network\*(R" order.
  3074.     f    A single-precision float in the native format.
  3075.     d    A double-precision float in the native format.
  3076.     p    A pointer to a string.
  3077.     v    A short in \*(L"VAX\*(R" (little-endian) order.
  3078.     V    A long in \*(L"VAX\*(R" (little-endian) order.
  3079.     x    A null byte.
  3080.     X    Back up a byte.
  3081.     @    Null fill to absolute position.
  3082.     u    A uuencoded string.
  3083.     b    A bit string (ascending bit order, like vec()).
  3084.     B    A bit string (descending bit order).
  3085.     h    A hex string (low nybble first).
  3086.     H    A hex string (high nybble first).
  3087.  
  3088. .fi
  3089. Each letter may optionally be followed by a number which gives a repeat
  3090. count.
  3091. With all types except "a", "A", "b", "B", "h" and "H",
  3092. the pack function will gobble up that many values
  3093. from the LIST.
  3094. A * for the repeat count means to use however many items are left.
  3095. The "a" and "A" types gobble just one value, but pack it as a string of length
  3096. count,
  3097. padding with nulls or spaces as necessary.
  3098. (When unpacking, "A" strips trailing spaces and nulls, but "a" does not.)
  3099. Likewise, the "b" and "B" fields pack a string that many bits long.
  3100. The "h" and "H" fields pack a string that many nybbles long.
  3101. Real numbers (floats and doubles) are in the native machine format
  3102. only; due to the multiplicity of floating formats around, and the lack
  3103. of a standard \*(L"network\*(R" representation, no facility for
  3104. interchange has been made.
  3105. This means that packed floating point data
  3106. written on one machine may not be readable on another - even if both
  3107. use IEEE floating point arithmetic (as the endian-ness of the memory
  3108. representation is not part of the IEEE spec).
  3109. Note that perl uses
  3110. doubles internally for all numeric calculation, and converting from
  3111. double -> float -> double will lose precision (i.e. unpack("f",
  3112. pack("f", $foo)) will not in general equal $foo).
  3113. .br
  3114. Examples:
  3115. .nf
  3116.  
  3117.     $foo = pack("cccc",65,66,67,68);
  3118.     # foo eq "ABCD"
  3119.     $foo = pack("c4",65,66,67,68);
  3120.     # same thing
  3121.  
  3122.     $foo = pack("ccxxcc",65,66,67,68);
  3123.     # foo eq "AB\e0\e0CD"
  3124.  
  3125.     $foo = pack("s2",1,2);
  3126.     # "\e1\e0\e2\e0" on little-endian
  3127.     # "\e0\e1\e0\e2" on big-endian
  3128.  
  3129.     $foo = pack("a4","abcd","x","y","z");
  3130.     # "abcd"
  3131.  
  3132.     $foo = pack("aaaa","abcd","x","y","z");
  3133.     # "axyz"
  3134.  
  3135.     $foo = pack("a14","abcdefg");
  3136.     # "abcdefg\e0\e0\e0\e0\e0\e0\e0"
  3137.  
  3138.     $foo = pack("i9pl", gmtime);
  3139.     # a real struct tm (on my system anyway)
  3140.  
  3141.     sub bintodec {
  3142.         unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
  3143.     }
  3144. .fi
  3145. The same template may generally also be used in the unpack function.
  3146. .Ip "pipe(READHANDLE,WRITEHANDLE)" 8 3
  3147. Opens a pair of connected pipes like the corresponding system call.
  3148. Note that if you set up a loop of piped processes, deadlock can occur
  3149. unless you are very careful.
  3150. In addition, note that perl's pipes use stdio buffering, so you may need
  3151. to set $| to flush your WRITEHANDLE after each command, depending on
  3152. the application.
  3153. [Requires version 3.0 patchlevel 9.]
  3154. .Ip "pop(ARRAY)" 8
  3155. .Ip "pop ARRAY" 8 6
  3156. Pops and returns the last value of the array, shortening the array by 1.
  3157. Has the same effect as
  3158. .nf
  3159.  
  3160.     $tmp = $ARRAY[$#ARRAY\-\|\-];
  3161.  
  3162. .fi
  3163. If there are no elements in the array, returns the undefined value.
  3164. .Ip "print(FILEHANDLE LIST)" 8 10
  3165. .Ip "print(LIST)" 8
  3166. .Ip "print FILEHANDLE LIST" 8
  3167. .Ip "print LIST" 8
  3168. .Ip "print" 8
  3169. Prints a string or a comma-separated list of strings.
  3170. Returns non-zero if successful.
  3171. FILEHANDLE may be a scalar variable name, in which case the variable contains
  3172. the name of the filehandle, thus introducing one level of indirection.
  3173. (NOTE: If FILEHANDLE is a variable and the next token is a term, it may be
  3174. misinterpreted as an operator unless you interpose a + or put parens around
  3175. the arguments.)
  3176. If FILEHANDLE is omitted, prints by default to standard output (or to the
  3177. last selected output channel\*(--see select()).
  3178. If LIST is also omitted, prints $_ to
  3179. .IR STDOUT .
  3180. To set the default output channel to something other than
  3181. .I STDOUT
  3182. use the select operation.
  3183. Note that, because print takes a LIST, anything in the LIST is evaluated
  3184. in an array context, and any subroutine that you call will have one or more
  3185. of its expressions evaluated in an array context.
  3186. Also be careful not to follow the print keyword with a left parenthesis
  3187. unless you want the corresponding right parenthesis to terminate the
  3188. arguments to the print\*(--interpose a + or put parens around all the arguments.
  3189. .Ip "printf(FILEHANDLE LIST)" 8 10
  3190. .Ip "printf(LIST)" 8
  3191. .Ip "printf FILEHANDLE LIST" 8
  3192. .Ip "printf LIST" 8
  3193. Equivalent to a \*(L"print FILEHANDLE sprintf(LIST)\*(R".
  3194. .Ip "push(ARRAY,LIST)" 8 7
  3195. Treats ARRAY (@ is optional) as a stack, and pushes the values of LIST
  3196. onto the end of ARRAY.
  3197. The length of ARRAY increases by the length of LIST.
  3198. Has the same effect as
  3199. .nf
  3200.  
  3201.     for $value (LIST) {
  3202.         $ARRAY[++$#ARRAY] = $value;
  3203.     }
  3204.  
  3205. .fi
  3206. but is more efficient.
  3207. .Ip "q/STRING/" 8 5
  3208. .Ip "qq/STRING/" 8
  3209. .Ip "qx/STRING/" 8
  3210. These are not really functions, but simply syntactic sugar to let you
  3211. avoid putting too many backslashes into quoted strings.
  3212. The q operator is a generalized single quote, and the qq operator a
  3213. generalized double quote.
  3214. The qx operator is a generalized backquote.
  3215. Any non-alphanumeric delimiter can be used in place of /, including newline.
  3216. If the delimiter is an opening bracket or parenthesis, the final delimiter
  3217. will be the corresponding closing bracket or parenthesis.
  3218. (Embedded occurrences of the closing bracket need to be backslashed as usual.)
  3219. Examples:
  3220. .nf
  3221.  
  3222. .ne 5
  3223.     $foo = q!I said, "You said, \'She said it.\'"!;
  3224.     $bar = q(\'This is it.\');
  3225.     $today = qx{ date };
  3226.     $_ .= qq
  3227. *** The previous line contains the naughty word "$&".\en
  3228.         if /(ibm|apple|awk)/;      # :-)
  3229.  
  3230. .fi
  3231. .Ip "rand(EXPR)" 8 8
  3232. .Ip "rand EXPR" 8
  3233. .Ip "rand" 8
  3234. Returns a random fractional number between 0 and the value of EXPR.
  3235. (EXPR should be positive.)
  3236. If EXPR is omitted, returns a value between 0 and 1.
  3237. See also srand().
  3238. .Ip "read(FILEHANDLE,SCALAR,LENGTH,OFFSET)" 8 5
  3239. .Ip "read(FILEHANDLE,SCALAR,LENGTH)" 8 5
  3240. Attempts to read LENGTH bytes of data into variable SCALAR from the specified
  3241. FILEHANDLE.
  3242. Returns the number of bytes actually read, or undef if there was an error.
  3243. SCALAR will be grown or shrunk to the length actually read.
  3244. An OFFSET may be specified to place the read data at some other place
  3245. than the beginning of the string.
  3246. This call is actually implemented in terms of stdio's fread call.  To get
  3247. a true read system call, see sysread.
  3248. .Ip "readdir(DIRHANDLE)" 8 3
  3249. .Ip "readdir DIRHANDLE" 8
  3250. Returns the next directory entry for a directory opened by opendir().
  3251. If used in an array context, returns all the rest of the entries in the
  3252. directory.
  3253. If there are no more entries, returns an undefined value in a scalar context
  3254. or a null list in an array context.
  3255. .Ip "readlink(EXPR)" 8 6
  3256. .Ip "readlink EXPR" 8
  3257. Returns the value of a symbolic link, if symbolic links are implemented.
  3258. If not, gives a fatal error.
  3259. If there is some system error, returns the undefined value and sets $! (errno).
  3260. If EXPR is omitted, uses $_.
  3261. .Ip "recv(SOCKET,SCALAR,LEN,FLAGS)" 8 4
  3262. Receives a message on a socket.
  3263. Attempts to receive LENGTH bytes of data into variable SCALAR from the specified
  3264. SOCKET filehandle.
  3265. Returns the address of the sender, or the undefined value if there's an error.
  3266. SCALAR will be grown or shrunk to the length actually read.
  3267. Takes the same flags as the system call of the same name.
  3268. .Ip "redo LABEL" 8 8
  3269. .Ip "redo" 8
  3270. The
  3271. .I redo
  3272. command restarts the loop block without evaluating the conditional again.
  3273. The
  3274. .I continue
  3275. block, if any, is not executed.
  3276. If the LABEL is omitted, the command refers to the innermost enclosing loop.
  3277. This command is normally used by programs that want to lie to themselves
  3278. about what was just input:
  3279. .nf
  3280.  
  3281. .ne 16
  3282.     # a simpleminded Pascal comment stripper
  3283.     # (warning: assumes no { or } in strings)
  3284.     line: while (<STDIN>) {
  3285.         while (s|\|({.*}.*\|){.*}|$1 \||) {}
  3286.         s|{.*}| \||;
  3287.         if (s|{.*| \||) {
  3288.             $front = $_;
  3289.             while (<STDIN>) {
  3290.                 if (\|/\|}/\|) {    # end of comment?
  3291.                     s|^|$front{|;
  3292.                     redo line;
  3293.                 }
  3294.             }
  3295.         }
  3296.         print;
  3297.     }
  3298.  
  3299. .fi
  3300. .Ip "rename(OLDNAME,NEWNAME)" 8 2
  3301. Changes the name of a file.
  3302. Returns 1 for success, 0 otherwise.
  3303. Will not work across filesystem boundaries.
  3304. .Ip "require(EXPR)" 8 6
  3305. .Ip "require EXPR" 8
  3306. .Ip "require" 8
  3307. Includes the library file specified by EXPR, or by $_ if EXPR is not supplied.
  3308. Has semantics similar to the following subroutine:
  3309. .nf
  3310.  
  3311.     sub require {
  3312.         local($filename) = @_;
  3313.         return 1 if $INC{$filename};
  3314.         local($realfilename,$result);
  3315.         ITER: {
  3316.         foreach $prefix (@INC) {
  3317.             $realfilename = "$prefix/$filename";
  3318.             if (-f $realfilename) {
  3319.             $result = do $realfilename;
  3320.             last ITER;
  3321.             }
  3322.         }
  3323.         die "Can't find $filename in \e@INC";
  3324.         }
  3325.         die $@ if $@;
  3326.         die "$filename did not return true value" unless $result;
  3327.         $INC{$filename} = $realfilename;
  3328.         $result;
  3329.     }
  3330.  
  3331. .fi
  3332. Note that the file will not be included twice under the same specified name.
  3333. .Ip "reset(EXPR)" 8 6
  3334. .Ip "reset EXPR" 8
  3335. .Ip "reset" 8
  3336. Generally used in a
  3337. .I continue
  3338. block at the end of a loop to clear variables and reset ?? searches
  3339. so that they work again.
  3340. The expression is interpreted as a list of single characters (hyphens allowed
  3341. for ranges).
  3342. All variables and arrays beginning with one of those letters are reset to
  3343. their pristine state.
  3344. If the expression is omitted, one-match searches (?pattern?) are reset to
  3345. match again.
  3346. Only resets variables or searches in the current package.
  3347. Always returns 1.
  3348. Examples:
  3349. .nf
  3350.  
  3351. .ne 3
  3352.     reset \'X\';    \h'|2i'# reset all X variables
  3353.     reset \'a\-z\';\h'|2i'# reset lower case variables
  3354.     reset;    \h'|2i'# just reset ?? searches
  3355.  
  3356. .fi
  3357. Note: resetting \*(L"A\-Z\*(R" is not recommended since you'll wipe out your ARGV and ENV
  3358. arrays.
  3359. .Sp
  3360. The use of reset on dbm associative arrays does not change the dbm file.
  3361. (It does, however, flush any entries cached by perl, which may be useful if
  3362. you are sharing the dbm file.
  3363. Then again, maybe not.)
  3364. .Ip "return LIST" 8 3
  3365. Returns from a subroutine with the value specified.
  3366. (Note that a subroutine can automatically return
  3367. the value of the last expression evaluated.
  3368. That's the preferred method\*(--use of an explicit
  3369. .I return
  3370. is a bit slower.)
  3371. .Ip "reverse(LIST)" 8 4
  3372. .Ip "reverse LIST" 8
  3373. In an array context, returns an array value consisting of the elements
  3374. of LIST in the opposite order.
  3375. In a scalar context, returns a string value consisting of the bytes of
  3376. the first element of LIST in the opposite order.
  3377. .Ip "rewinddir(DIRHANDLE)" 8 5
  3378. .Ip "rewinddir DIRHANDLE" 8
  3379. Sets the current position to the beginning of the directory for the readdir() routine on DIRHANDLE.
  3380. .Ip "rindex(STR,SUBSTR,POSITION)" 8 6
  3381. .Ip "rindex(STR,SUBSTR)" 8 4
  3382. Works just like index except that it
  3383. returns the position of the LAST occurrence of SUBSTR in STR.
  3384. If POSITION is specified, returns the last occurrence at or before that
  3385. position.
  3386. .Ip "rmdir(FILENAME)" 8 4
  3387. .Ip "rmdir FILENAME" 8
  3388. Deletes the directory specified by FILENAME if it is empty.
  3389. If it succeeds it returns 1, otherwise it returns 0 and sets $! (errno).
  3390. If FILENAME is omitted, uses $_.
  3391. .Ip "s/PATTERN/REPLACEMENT/gieo" 8 3
  3392. Searches a string for a pattern, and if found, replaces that pattern with the
  3393. replacement text and returns the number of substitutions made.
  3394. Otherwise it returns false (0).
  3395. The \*(L"g\*(R" is optional, and if present, indicates that all occurrences
  3396. of the pattern are to be replaced.
  3397. The \*(L"i\*(R" is also optional, and if present, indicates that matching
  3398. is to be done in a case-insensitive manner.
  3399. The \*(L"e\*(R" is likewise optional, and if present, indicates that
  3400. the replacement string is to be evaluated as an expression rather than just
  3401. as a double-quoted string.
  3402. Any non-alphanumeric delimiter may replace the slashes;
  3403. if single quotes are used, no
  3404. interpretation is done on the replacement string (the e modifier overrides
  3405. this, however); if backquotes are used, the replacement string is a command
  3406. to execute whose output will be used as the actual replacement text.
  3407. If no string is specified via the =~ or !~ operator,
  3408. the $_ string is searched and modified.
  3409. (The string specified with =~ must be a scalar variable, an array element,
  3410. or an assignment to one of those, i.e. an lvalue.)
  3411. If the pattern contains a $ that looks like a variable rather than an
  3412. end-of-string test, the variable will be interpolated into the pattern at
  3413. run-time.
  3414. If you only want the pattern compiled once the first time the variable is
  3415. interpolated, add an \*(L"o\*(R" at the end.
  3416. If the PATTERN evaluates to a null string, the most recent successful
  3417. regular expression is used instead.
  3418. See also the section on regular expressions.
  3419. Examples:
  3420. .nf
  3421.  
  3422.     s/\|\e\|bgreen\e\|b/mauve/g;        # don't change wintergreen
  3423.  
  3424.     $path \|=~ \|s|\|/usr/bin|\|/usr/local/bin|;
  3425.  
  3426.     s/Login: $foo/Login: $bar/; # run-time pattern
  3427.  
  3428.     ($foo = $bar) =~ s/bar/foo/;
  3429.  
  3430.     $_ = \'abc123xyz\';
  3431.     s/\ed+/$&*2/e;        # yields \*(L'abc246xyz\*(R'
  3432.     s/\ed+/sprintf("%5d",$&)/e;    # yields \*(L'abc  246xyz\*(R'
  3433.     s/\ew/$& x 2/eg;        # yields \*(L'aabbcc  224466xxyyzz\*(R'
  3434.  
  3435.     s/\|([^ \|]*\|) *\|([^ \|]*\|)\|/\|$2 $1/;    # reverse 1st two fields
  3436.  
  3437. .fi
  3438. (Note the use of $ instead of \|\e\| in the last example.  See section
  3439. on regular expressions.)
  3440. .Ip "scalar(EXPR)" 8 3
  3441. Forces EXPR to be interpreted in a scalar context and returns the value
  3442. of EXPR.
  3443. .Ip "seek(FILEHANDLE,POSITION,WHENCE)" 8 3
  3444. Randomly positions the file pointer for FILEHANDLE, just like the fseek()
  3445. call of stdio.
  3446. FILEHANDLE may be an expression whose value gives the name of the filehandle.
  3447. Returns 1 upon success, 0 otherwise.
  3448. .Ip "seekdir(DIRHANDLE,POS)" 8 3
  3449. Sets the current position for the readdir() routine on DIRHANDLE.
  3450. POS must be a value returned by telldir().
  3451. Has the same caveats about possible directory compaction as the corresponding
  3452. system library routine.
  3453. .Ip "select(FILEHANDLE)" 8 3
  3454. .Ip "select" 8 3
  3455. Returns the currently selected filehandle.
  3456. Sets the current default filehandle for output, if FILEHANDLE is supplied.
  3457. This has two effects: first, a
  3458. .I write
  3459. or a
  3460. .I print
  3461. without a filehandle will default to this FILEHANDLE.
  3462. Second, references to variables related to output will refer to this output
  3463. channel.
  3464. For example, if you have to set the top of form format for more than
  3465. one output channel, you might do the following:
  3466. .nf
  3467.  
  3468. .ne 4
  3469.     select(REPORT1);
  3470.     $^ = \'report1_top\';
  3471.     select(REPORT2);
  3472.     $^ = \'report2_top\';
  3473.  
  3474. .fi
  3475. FILEHANDLE may be an expression whose value gives the name of the actual filehandle.
  3476. Thus:
  3477. .nf
  3478.  
  3479.     $oldfh = select(STDERR); $| = 1; select($oldfh);
  3480.  
  3481. .fi
  3482. .Ip "select(RBITS,WBITS,EBITS,TIMEOUT)" 8 3
  3483. This calls the select system call with the bitmasks specified, which can
  3484. be constructed using fileno() and vec(), along these lines:
  3485. .nf
  3486.  
  3487.     $rin = $win = $ein = '';
  3488.     vec($rin,fileno(STDIN),1) = 1;
  3489.     vec($win,fileno(STDOUT),1) = 1;
  3490.     $ein = $rin | $win;
  3491.  
  3492. .fi
  3493. If you want to select on many filehandles you might wish to write a subroutine:
  3494. .nf
  3495.  
  3496.     sub fhbits {
  3497.         local(@fhlist) = split(' ',$_[0]);
  3498.         local($bits);
  3499.         for (@fhlist) {
  3500.         vec($bits,fileno($_),1) = 1;
  3501.         }
  3502.         $bits;
  3503.     }
  3504.     $rin = &fhbits('STDIN TTY SOCK');
  3505.  
  3506. .fi
  3507. The usual idiom is:
  3508. .nf
  3509.  
  3510.     ($nfound,$timeleft) =
  3511.       select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
  3512.  
  3513. or to block until something becomes ready:
  3514.  
  3515. .ie t \{\
  3516.     $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);
  3517. 'br\}
  3518. .el \{\
  3519.     $nfound = select($rout=$rin, $wout=$win,
  3520.                 $eout=$ein, undef);
  3521. 'br\}
  3522.  
  3523. .fi
  3524. Any of the bitmasks can also be undef.
  3525. The timeout, if specified, is in seconds, which may be fractional.
  3526. NOTE: not all implementations are capable of returning the $timeleft.
  3527. If not, they always return $timeleft equal to the supplied $timeout.
  3528. .Ip "semctl(ID,SEMNUM,CMD,ARG)" 8 4
  3529. Calls the System V IPC function semctl.  If CMD is &IPC_STAT or
  3530. &GETALL, then ARG must be a variable which will hold the returned
  3531. semid_ds structure or semaphore value array.  Returns like ioctl: the
  3532. undefined value for error, "0 but true" for zero, or the actual return
  3533. value otherwise.
  3534. .Ip "semget(KEY,NSEMS,SIZE,FLAGS)" 8 4
  3535. Calls the System V IPC function semget.  Returns the semaphore id, or
  3536. the undefined value if there is an error.
  3537. .Ip "semop(KEY,OPSTRING)" 8 4
  3538. Calls the System V IPC function semop to perform semaphore operations
  3539. such as signaling and waiting.  OPSTRING must be a packed array of
  3540. semop structures.  Each semop structure can be generated with
  3541. \&'pack("sss", $semnum, $semop, $semflag)'.  The number of semaphore
  3542. operations is implied by the length of OPSTRING.  Returns true if
  3543. successful, or false if there is an error.  As an example, the
  3544. following code waits on semaphore $semnum of semaphore id $semid:
  3545. .nf
  3546.  
  3547.     $semop = pack("sss", $semnum, -1, 0);
  3548.     die "Semaphore trouble: $!\en" unless semop($semid, $semop);
  3549.  
  3550. .fi
  3551. To signal the semaphore, replace "-1" with "1".
  3552. .Ip "send(SOCKET,MSG,FLAGS,TO)" 8 4
  3553. .Ip "send(SOCKET,MSG,FLAGS)" 8
  3554. Sends a message on a socket.
  3555. Takes the same flags as the system call of the same name.
  3556. On unconnected sockets you must specify a destination to send TO.
  3557. Returns the number of characters sent, or the undefined value if
  3558. there is an error.
  3559. .Ip "setpgrp(PID,PGRP)" 8 4
  3560. Sets the current process group for the specified PID, 0 for the current
  3561. process.
  3562. Will produce a fatal error if used on a machine that doesn't implement
  3563. setpgrp(2).
  3564. .Ip "setpriority(WHICH,WHO,PRIORITY)" 8 4
  3565. Sets the current priority for a process, a process group, or a user.
  3566. (See setpriority(2).)
  3567. Will produce a fatal error if used on a machine that doesn't implement
  3568. setpriority(2).
  3569. .Ip "setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)" 8 3
  3570. Sets the socket option requested.
  3571. Returns undefined if there is an error.
  3572. OPTVAL may be specified as undef if you don't want to pass an argument.
  3573. .Ip "shift(ARRAY)" 8 6
  3574. .Ip "shift ARRAY" 8
  3575. .Ip "shift" 8
  3576. Shifts the first value of the array off and returns it,
  3577. shortening the array by 1 and moving everything down.
  3578. If there are no elements in the array, returns the undefined value.
  3579. If ARRAY is omitted, shifts the @ARGV array in the main program, and the @_
  3580. array in subroutines.
  3581. (This is determined lexically.)
  3582. See also unshift(), push() and pop().
  3583. Shift() and unshift() do the same thing to the left end of an array that push()
  3584. and pop() do to the right end.
  3585. .Ip "shmctl(ID,CMD,ARG)" 8 4
  3586. Calls the System V IPC function shmctl.  If CMD is &IPC_STAT, then ARG
  3587. must be a variable which will hold the returned shmid_ds structure.
  3588. Returns like ioctl: the undefined value for error, "0 but true" for
  3589. zero, or the actual return value otherwise.
  3590. .Ip "shmget(KEY,SIZE,FLAGS)" 8 4
  3591. Calls the System V IPC function shmget.  Returns the shared memory
  3592. segment id, or the undefined value if there is an error.
  3593. .Ip "shmread(ID,VAR,POS,SIZE)" 8 4
  3594. .Ip "shmwrite(ID,STRING,POS,SIZE)" 8
  3595. Reads or writes the System V shared memory segment ID starting at
  3596. position POS for size SIZE by attaching to it, copying in/out, and
  3597. detaching from it.  When reading, VAR must be a variable which
  3598. will hold the data read.  When writing, if STRING is too long,
  3599. only SIZE bytes are used; if STRING is too short, nulls are
  3600. written to fill out SIZE bytes.  Return true if successful, or
  3601. false if there is an error.
  3602. .Ip "shutdown(SOCKET,HOW)" 8 3
  3603. Shuts down a socket connection in the manner indicated by HOW, which has
  3604. the same interpretation as in the system call of the same name.
  3605. .Ip "sin(EXPR)" 8 4
  3606. .Ip "sin EXPR" 8
  3607. Returns the sine of EXPR (expressed in radians).
  3608. If EXPR is omitted, returns sine of $_.
  3609. .Ip "sleep(EXPR)" 8 6
  3610. .Ip "sleep EXPR" 8
  3611. .Ip "sleep" 8
  3612. Causes the script to sleep for EXPR seconds, or forever if no EXPR.
  3613. May be interrupted by sending the process a SIGALRM.
  3614. Returns the number of seconds actually slept.
  3615. You probably cannot mix alarm() and sleep() calls, since sleep() is
  3616. often implemented using alarm().
  3617. .Ip "socket(SOCKET,DOMAIN,TYPE,PROTOCOL)" 8 3
  3618. Opens a socket of the specified kind and attaches it to filehandle SOCKET.
  3619. DOMAIN, TYPE and PROTOCOL are specified the same as for the system call
  3620. of the same name.
  3621. You may need to run h2ph on sys/socket.h to get the proper values handy
  3622. in a perl library file.
  3623. Return true if successful.
  3624. See the example in the section on Interprocess Communication.
  3625. .Ip "socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)" 8 3
  3626. Creates an unnamed pair of sockets in the specified domain, of the specified
  3627. type.
  3628. DOMAIN, TYPE and PROTOCOL are specified the same as for the system call
  3629. of the same name.
  3630. If unimplemented, yields a fatal error.
  3631. Return true if successful.
  3632. .Ip "sort(SUBROUTINE LIST)" 8 9
  3633. .Ip "sort(LIST)" 8
  3634. .Ip "sort SUBROUTINE LIST" 8
  3635. .Ip "sort BLOCK LIST" 8
  3636. .Ip "sort LIST" 8
  3637. Sorts the LIST and returns the sorted array value.
  3638. Nonexistent values of arrays are stripped out.
  3639. If SUBROUTINE or BLOCK is omitted, sorts in standard string comparison order.
  3640. If SUBROUTINE is specified, gives the name of a subroutine that returns
  3641. an integer less than, equal to, or greater than 0,
  3642. depending on how the elements of the array are to be ordered.
  3643. (The <=> and cmp operators are extremely useful in such routines.)
  3644. SUBROUTINE may be a scalar variable name, in which case the value provides
  3645. the name of the subroutine to use.
  3646. In place of a SUBROUTINE name, you can provide a BLOCK as an anonymous,
  3647. in-line sort subroutine.
  3648. .Sp
  3649. In the interests of efficiency the normal calling code for subroutines
  3650. is bypassed, with the following effects: the subroutine may not be a recursive
  3651. subroutine, and the two elements to be compared are passed into the subroutine
  3652. not via @_ but as $a and $b (see example below).
  3653. They are passed by reference so don't modify $a and $b.
  3654. .Sp
  3655. Examples:
  3656. .nf
  3657.  
  3658. .ne 2
  3659.     # sort lexically
  3660.     @articles = sort @files;
  3661.  
  3662. .ne 2
  3663.     # same thing, but with explicit sort routine
  3664.     @articles = sort {$a cmp $b;} @files;
  3665.  
  3666. .ne 2
  3667.     # same thing in reversed order
  3668.     @articles = sort {$b cmp $a;} @files;
  3669.  
  3670. .ne 2
  3671.     # sort numerically ascending
  3672.     @articles = sort {$a <=> $b;} @files;
  3673.  
  3674. .ne 2
  3675.     # sort numerically descending
  3676.     @articles = sort {$b <=> $a;} @files;
  3677.  
  3678. .ne 5
  3679.     # sort using explicit subroutine name
  3680.     sub byage {
  3681.         $age{$a} <=> $age{$b};    # presuming integers
  3682.     }
  3683.     @sortedclass = sort byage @class;
  3684.  
  3685. .ne 9
  3686.     sub reverse { $b cmp $a; }
  3687.     @harry = (\'dog\',\'cat\',\'x\',\'Cain\',\'Abel\');
  3688.     @george = (\'gone\',\'chased\',\'yz\',\'Punished\',\'Axed\');
  3689.     print sort @harry;
  3690.         # prints AbelCaincatdogx
  3691.     print sort reverse @harry;
  3692.         # prints xdogcatCainAbel
  3693.     print sort @george, \'to\', @harry;
  3694.         # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
  3695.  
  3696. .fi
  3697. .Ip "splice(ARRAY,OFFSET,LENGTH,LIST)" 8 8
  3698. .Ip "splice(ARRAY,OFFSET,LENGTH)" 8
  3699. .Ip "splice(ARRAY,OFFSET)" 8
  3700. Removes the elements designated by OFFSET and LENGTH from an array, and
  3701. replaces them with the elements of LIST, if any.
  3702. Returns the elements removed from the array.
  3703. The array grows or shrinks as necessary.
  3704. If LENGTH is omitted, removes everything from OFFSET onward.
  3705. The following equivalencies hold (assuming $[ == 0):
  3706. .nf
  3707.  
  3708.     push(@a,$x,$y)\h'|3.5i'splice(@a,$#a+1,0,$x,$y)
  3709.     pop(@a)\h'|3.5i'splice(@a,-1)
  3710.     shift(@a)\h'|3.5i'splice(@a,0,1)
  3711.     unshift(@a,$x,$y)\h'|3.5i'splice(@a,0,0,$x,$y)
  3712.     $a[$x] = $y\h'|3.5i'splice(@a,$x,1,$y);
  3713.  
  3714. Example, assuming array lengths are passed before arrays:
  3715.     
  3716.     sub aeq {    # compare two array values
  3717.         local(@a) = splice(@_,0,shift);
  3718.         local(@b) = splice(@_,0,shift);
  3719.         return 0 unless @a == @b;    # same len?
  3720.         while (@a) {
  3721.             return 0 if pop(@a) ne pop(@b);
  3722.         }
  3723.         return 1;
  3724.     }
  3725.     if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
  3726.  
  3727. .fi
  3728. .Ip "split(/PATTERN/,EXPR,LIMIT)" 8 8
  3729. .Ip "split(/PATTERN/,EXPR)" 8 8
  3730. .Ip "split(/PATTERN/)" 8
  3731. .Ip "split" 8
  3732. Splits a string into an array of strings, and returns it.
  3733. (If not in an array context, returns the number of fields found and splits
  3734. into the @_ array.
  3735. (In an array context, you can force the split into @_
  3736. by using ?? as the pattern delimiters, but it still returns the array value.))
  3737. If EXPR is omitted, splits the $_ string.
  3738. If PATTERN is also omitted, splits on whitespace (/[\ \et\en]+/).
  3739. Anything matching PATTERN is taken to be a delimiter separating the fields.
  3740. (Note that the delimiter may be longer than one character.)
  3741. If LIMIT is specified, splits into no more than that many fields (though it
  3742. may split into fewer).
  3743. If LIMIT is unspecified, trailing null fields are stripped (which
  3744. potential users of pop() would do well to remember).
  3745. A pattern matching the null string (not to be confused with a null pattern //,
  3746. which is just one member of the set of patterns matching a null string)
  3747. will split the value of EXPR into separate characters at each point it
  3748. matches that way.
  3749. For example:
  3750. .nf
  3751.  
  3752.     print join(\':\', split(/ */, \'hi there\'));
  3753.  
  3754. .fi
  3755. produces the output \*(L'h:i:t:h:e:r:e\*(R'.
  3756. .Sp
  3757. The LIMIT parameter can be used to partially split a line
  3758. .nf
  3759.  
  3760.     ($login, $passwd, $remainder) = split(\|/\|:\|/\|, $_, 3);
  3761.  
  3762. .fi
  3763. (When assigning to a list, if LIMIT is omitted, perl supplies a LIMIT one
  3764. larger than the number of variables in the list, to avoid unnecessary work.
  3765. For the list above LIMIT would have been 4 by default.
  3766. In time critical applications it behooves you not to split into
  3767. more fields than you really need.)
  3768. .Sp
  3769. If the PATTERN contains parentheses, additional array elements are created
  3770. from each matching substring in the delimiter.
  3771. .Sp
  3772.     split(/([,-])/,"1-10,20");
  3773. .Sp
  3774. produces the array value
  3775. .Sp
  3776.     (1,'-',10,',',20)
  3777. .Sp
  3778. The pattern /PATTERN/ may be replaced with an expression to specify patterns
  3779. that vary at runtime.
  3780. (To do runtime compilation only once, use /$variable/o.)
  3781. As a special case, specifying a space (\'\ \') will split on white space
  3782. just as split with no arguments does, but leading white space does NOT
  3783. produce a null first field.
  3784. Thus, split(\'\ \') can be used to emulate
  3785. .IR awk 's
  3786. default behavior, whereas
  3787. split(/\ /) will give you as many null initial fields as there are
  3788. leading spaces.
  3789. .Sp
  3790. Example:
  3791. .nf
  3792.  
  3793. .ne 5
  3794.     open(passwd, \'/etc/passwd\');
  3795.     while (<passwd>) {
  3796. .ie t \{\
  3797.         ($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(\|/\|:\|/\|);
  3798. 'br\}
  3799. .el \{\
  3800.         ($login, $passwd, $uid, $gid, $gcos, $home, $shell)
  3801.             = split(\|/\|:\|/\|);
  3802. 'br\}
  3803.         .\|.\|.
  3804.     }
  3805.  
  3806. .fi
  3807. (Note that $shell above will still have a newline on it.  See chop().)
  3808. See also
  3809. .IR join .
  3810. .Ip "sprintf(FORMAT,LIST)" 8 4
  3811. Returns a string formatted by the usual printf conventions.
  3812. The * character is not supported.
  3813. .Ip "sqrt(EXPR)" 8 4
  3814. .Ip "sqrt EXPR" 8
  3815. Return the square root of EXPR.
  3816. If EXPR is omitted, returns square root of $_.
  3817. .Ip "srand(EXPR)" 8 4
  3818. .Ip "srand EXPR" 8
  3819. Sets the random number seed for the
  3820. .I rand
  3821. operator.
  3822. If EXPR is omitted, does srand(time).
  3823. .Ip "stat(FILEHANDLE)" 8 8
  3824. .Ip "stat FILEHANDLE" 8
  3825. .Ip "stat(EXPR)" 8
  3826. .Ip "stat SCALARVARIABLE" 8
  3827. Returns a 13-element array giving the statistics for a file, either the file
  3828. opened via FILEHANDLE, or named by EXPR.
  3829. Typically used as follows:
  3830. .nf
  3831.  
  3832. .ne 3
  3833.     ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
  3834.        $atime,$mtime,$ctime,$blksize,$blocks)
  3835.            = stat($filename);
  3836.  
  3837. .fi
  3838. If stat is passed the special filehandle consisting of an underline,
  3839. no stat is done, but the current contents of the stat structure from
  3840. the last stat or filetest are returned.
  3841. Example:
  3842. .nf
  3843.  
  3844. .ne 3
  3845.     if (-x $file && (($d) = stat(_)) && $d < 0) {
  3846.         print "$file is executable NFS file\en";
  3847.     }
  3848.  
  3849. .fi
  3850. (This only works on machines for which the device number is negative under NFS.)
  3851. .Ip "study(SCALAR)" 8 6
  3852. .Ip "study SCALAR" 8
  3853. .Ip "study"
  3854. Takes extra time to study SCALAR ($_ if unspecified) in anticipation of
  3855. doing many pattern matches on the string before it is next modified.
  3856. This may or may not save time, depending on the nature and number of patterns
  3857. you are searching on, and on the distribution of character frequencies in
  3858. the string to be searched\*(--you probably want to compare runtimes with and
  3859. without it to see which runs faster.
  3860. Those loops which scan for many short constant strings (including the constant
  3861. parts of more complex patterns) will benefit most.
  3862. You may have only one study active at a time\*(--if you study a different
  3863. scalar the first is \*(L"unstudied\*(R".
  3864. (The way study works is this: a linked list of every character in the string
  3865. to be searched is made, so we know, for example, where all the \*(L'k\*(R' characters
  3866. are.
  3867. From each search string, the rarest character is selected, based on some
  3868. static frequency tables constructed from some C programs and English text.
  3869. Only those places that contain this \*(L"rarest\*(R" character are examined.)
  3870. .Sp
  3871. For example, here is a loop which inserts index producing entries before any line
  3872. containing a certain pattern:
  3873. .nf
  3874.  
  3875. .ne 8
  3876.     while (<>) {
  3877.         study;
  3878.         print ".IX foo\en" if /\ebfoo\eb/;
  3879.         print ".IX bar\en" if /\ebbar\eb/;
  3880.         print ".IX blurfl\en" if /\ebblurfl\eb/;
  3881.         .\|.\|.
  3882.         print;
  3883.     }
  3884.  
  3885. .fi
  3886. In searching for /\ebfoo\eb/, only those locations in $_ that contain \*(L'f\*(R'
  3887. will be looked at, because \*(L'f\*(R' is rarer than \*(L'o\*(R'.
  3888. In general, this is a big win except in pathological cases.
  3889. The only question is whether it saves you more time than it took to build
  3890. the linked list in the first place.
  3891. .Sp
  3892. Note that if you have to look for strings that you don't know till runtime,
  3893. you can build an entire loop as a string and eval that to avoid recompiling
  3894. all your patterns all the time.
  3895. Together with undefining $/ to input entire files as one record, this can
  3896. be very fast, often faster than specialized programs like fgrep.
  3897. The following scans a list of files (@files)
  3898. for a list of words (@words), and prints out the names of those files that
  3899. contain a match:
  3900. .nf
  3901.  
  3902. .ne 12
  3903.     $search = \'while (<>) { study;\';
  3904.     foreach $word (@words) {
  3905.         $search .= "++\e$seen{\e$ARGV} if /\eb$word\eb/;\en";
  3906.     }
  3907.     $search .= "}";
  3908.     @ARGV = @files;
  3909.     undef $/;
  3910.     eval $search;        # this screams
  3911.     $/ = "\en";        # put back to normal input delim
  3912.     foreach $file (sort keys(%seen)) {
  3913.         print $file, "\en";
  3914.     }
  3915.  
  3916. .fi
  3917. .Ip "substr(EXPR,OFFSET,LEN)" 8 2
  3918. .Ip "substr(EXPR,OFFSET)" 8 2
  3919. Extracts a substring out of EXPR and returns it.
  3920. First character is at offset 0, or whatever you've set $[ to.
  3921. If OFFSET is negative, starts that far from the end of the string.
  3922. If LEN is omitted, returns everything to the end of the string.
  3923. You can use the substr() function as an lvalue, in which case EXPR must
  3924. be an lvalue.
  3925. If you assign something shorter than LEN, the string will shrink, and
  3926. if you assign something longer than LEN, the string will grow to accommodate it.
  3927. To keep the string the same length you may need to pad or chop your value using
  3928. sprintf().
  3929. .Ip "symlink(OLDFILE,NEWFILE)" 8 2
  3930. Creates a new filename symbolically linked to the old filename.
  3931. Returns 1 for success, 0 otherwise.
  3932. On systems that don't support symbolic links, produces a fatal error at
  3933. run time.
  3934. To check for that, use eval:
  3935. .nf
  3936.  
  3937.     $symlink_exists = (eval \'symlink("","");\', $@ eq \'\');
  3938.  
  3939. .fi
  3940. .Ip "syscall(LIST)" 8 6
  3941. .Ip "syscall LIST" 8
  3942. Calls the system call specified as the first element of the list, passing
  3943. the remaining elements as arguments to the system call.
  3944. If unimplemented, produces a fatal error.
  3945. The arguments are interpreted as follows: if a given argument is numeric,
  3946. the argument is passed as an int.
  3947. If not, the pointer to the string value is passed.
  3948. You are responsible to make sure a string is pre-extended long enough
  3949. to receive any result that might be written into a string.
  3950. If your integer arguments are not literals and have never been interpreted
  3951. in a numeric context, you may need to add 0 to them to force them to look
  3952. like numbers.
  3953. .nf
  3954.  
  3955.     require 'syscall.ph';        # may need to run h2ph
  3956.     syscall(&SYS_write, fileno(STDOUT), "hi there\en", 9);
  3957.  
  3958. .fi
  3959. .Ip "sysread(FILEHANDLE,SCALAR,LENGTH,OFFSET)" 8 5
  3960. .Ip "sysread(FILEHANDLE,SCALAR,LENGTH)" 8 5
  3961. Attempts to read LENGTH bytes of data into variable SCALAR from the specified
  3962. FILEHANDLE, using the system call read(2).
  3963. It bypasses stdio, so mixing this with other kinds of reads may cause
  3964. confusion.
  3965. Returns the number of bytes actually read, or undef if there was an error.
  3966. SCALAR will be grown or shrunk to the length actually read.
  3967. An OFFSET may be specified to place the read data at some other place
  3968. than the beginning of the string.
  3969. .Ip "system(LIST)" 8 6
  3970. .Ip "system LIST" 8
  3971. Does exactly the same thing as \*(L"exec LIST\*(R" except that a fork
  3972. is done first, and the parent process waits for the child process to complete.
  3973. Note that argument processing varies depending on the number of arguments.
  3974. The return value is the exit status of the program as returned by the wait()
  3975. call.
  3976. To get the actual exit value divide by 256.
  3977. See also
  3978. .IR exec .
  3979. .Ip "syswrite(FILEHANDLE,SCALAR,LENGTH,OFFSET)" 8 5
  3980. .Ip "syswrite(FILEHANDLE,SCALAR,LENGTH)" 8 5
  3981. Attempts to write LENGTH bytes of data from variable SCALAR to the specified
  3982. FILEHANDLE, using the system call write(2).
  3983. It bypasses stdio, so mixing this with prints may cause
  3984. confusion.
  3985. Returns the number of bytes actually written, or undef if there was an error.
  3986. An OFFSET may be specified to place the read data at some other place
  3987. than the beginning of the string.
  3988. .Ip "tell(FILEHANDLE)" 8 6
  3989. .Ip "tell FILEHANDLE" 8 6
  3990. .Ip "tell" 8
  3991. Returns the current file position for FILEHANDLE.
  3992. FILEHANDLE may be an expression whose value gives the name of the actual
  3993. filehandle.
  3994. If FILEHANDLE is omitted, assumes the file last read.
  3995. .Ip "telldir(DIRHANDLE)" 8 5
  3996. .Ip "telldir DIRHANDLE" 8
  3997. Returns the current position of the readdir() routines on DIRHANDLE.
  3998. Value may be given to seekdir() to access a particular location in
  3999. a directory.
  4000. Has the same caveats about possible directory compaction as the corresponding
  4001. system library routine.
  4002. .Ip "time" 8 4
  4003. Returns the number of non-leap seconds since 00:00:00 UTC, January 1, 1970.
  4004. Suitable for feeding to gmtime() and localtime().
  4005. .Ip "times" 8 4
  4006. Returns a four-element array giving the user and system times, in seconds, for this
  4007. process and the children of this process.
  4008. .Sp
  4009.     ($user,$system,$cuser,$csystem) = times;
  4010. .Sp
  4011. .Ip "tr/SEARCHLIST/REPLACEMENTLIST/cds" 8 5
  4012. .Ip "y/SEARCHLIST/REPLACEMENTLIST/cds" 8
  4013. Translates all occurrences of the characters found in the search list with
  4014. the corresponding character in the replacement list.
  4015. It returns the number of characters replaced or deleted.
  4016. If no string is specified via the =~ or !~ operator,
  4017. the $_ string is translated.
  4018. (The string specified with =~ must be a scalar variable, an array element,
  4019. or an assignment to one of those, i.e. an lvalue.)
  4020. For
  4021. .I sed
  4022. devotees,
  4023. .I y
  4024. is provided as a synonym for
  4025. .IR tr .
  4026. .Sp
  4027. If the c modifier is specified, the SEARCHLIST character set is complemented.
  4028. If the d modifier is specified, any characters specified by SEARCHLIST that
  4029. are not found in REPLACEMENTLIST are deleted.
  4030. (Note that this is slightly more flexible than the behavior of some
  4031. .I tr
  4032. programs, which delete anything they find in the SEARCHLIST, period.)
  4033. If the s modifier is specified, sequences of characters that were translated
  4034. to the same character are squashed down to 1 instance of the character.
  4035. .Sp
  4036. If the d modifier was used, the REPLACEMENTLIST is always interpreted exactly
  4037. as specified.
  4038. Otherwise, if the REPLACEMENTLIST is shorter than the SEARCHLIST,
  4039. the final character is replicated till it is long enough.
  4040. If the REPLACEMENTLIST is null, the SEARCHLIST is replicated.
  4041. This latter is useful for counting characters in a class, or for squashing
  4042. character sequences in a class.
  4043. .Sp
  4044. Examples:
  4045. .nf
  4046.  
  4047.     $ARGV[1] \|=~ \|y/A\-Z/a\-z/;    \h'|3i'# canonicalize to lower case
  4048.  
  4049.     $cnt = tr/*/*/;        \h'|3i'# count the stars in $_
  4050.  
  4051.     $cnt = tr/0\-9//;        \h'|3i'# count the digits in $_
  4052.  
  4053.     tr/a\-zA\-Z//s;    \h'|3i'# bookkeeper \-> bokeper
  4054.  
  4055.     ($HOST = $host) =~ tr/a\-z/A\-Z/;
  4056.  
  4057.     y/a\-zA\-Z/ /cs;    \h'|3i'# change non-alphas to single space
  4058.  
  4059.     tr/\e200\-\e377/\e0\-\e177/;\h'|3i'# delete 8th bit
  4060.  
  4061. .fi
  4062. .Ip "truncate(FILEHANDLE,LENGTH)" 8 4
  4063. .Ip "truncate(EXPR,LENGTH)" 8
  4064. Truncates the file opened on FILEHANDLE, or named by EXPR, to the specified
  4065. length.
  4066. Produces a fatal error if truncate isn't implemented on your system.
  4067. .Ip "umask(EXPR)" 8 4
  4068. .Ip "umask EXPR" 8
  4069. .Ip "umask" 8
  4070. Sets the umask for the process and returns the old one.
  4071. If EXPR is omitted, merely returns current umask.
  4072. .Ip "undef(EXPR)" 8 6
  4073. .Ip "undef EXPR" 8
  4074. .Ip "undef" 8
  4075. Undefines the value of EXPR, which must be an lvalue.
  4076. Use only on a scalar value, an entire array, or a subroutine name (using &).
  4077. (Undef will probably not do what you expect on most predefined variables or
  4078. dbm array values.)
  4079. Always returns the undefined value.
  4080. You can omit the EXPR, in which case nothing is undefined, but you still
  4081. get an undefined value that you could, for instance, return from a subroutine.
  4082. Examples:
  4083. .nf
  4084.  
  4085. .ne 6
  4086.     undef $foo;
  4087.     undef $bar{'blurfl'};
  4088.     undef @ary;
  4089.     undef %assoc;
  4090.     undef &mysub;
  4091.     return (wantarray ? () : undef) if $they_blew_it;
  4092.  
  4093. .fi
  4094. .Ip "unlink(LIST)" 8 4
  4095. .Ip "unlink LIST" 8
  4096. Deletes a list of files.
  4097. Returns the number of files successfully deleted.
  4098. .nf
  4099.  
  4100. .ne 2
  4101.     $cnt = unlink \'a\', \'b\', \'c\';
  4102.     unlink @goners;
  4103.     unlink <*.bak>;
  4104.  
  4105. .fi
  4106. Note: unlink will not delete directories unless you are superuser and the
  4107. .B \-U
  4108. flag is supplied to
  4109. .IR perl .
  4110. Even if these conditions are met, be warned that unlinking a directory
  4111. can inflict damage on your filesystem.
  4112. Use rmdir instead.
  4113. .Ip "unpack(TEMPLATE,EXPR)" 8 4
  4114. Unpack does the reverse of pack: it takes a string representing
  4115. a structure and expands it out into an array value, returning the array
  4116. value.
  4117. (In a scalar context, it merely returns the first value produced.)
  4118. The TEMPLATE has the same format as in the pack function.
  4119. Here's a subroutine that does substring:
  4120. .nf
  4121.  
  4122. .ne 4
  4123.     sub substr {
  4124.         local($what,$where,$howmuch) = @_;
  4125.         unpack("x$where a$howmuch", $what);
  4126.     }
  4127.  
  4128. .ne 3
  4129. and then there's
  4130.  
  4131.     sub ord { unpack("c",$_[0]); }
  4132.  
  4133. .fi
  4134. In addition, you may prefix a field with a %<number> to indicate that
  4135. you want a <number>-bit checksum of the items instead of the items themselves.
  4136. Default is a 16-bit checksum.
  4137. For example, the following computes the same number as the System V sum program:
  4138. .nf
  4139.  
  4140. .ne 4
  4141.     while (<>) {
  4142.         $checksum += unpack("%16C*", $_);
  4143.     }
  4144.     $checksum %= 65536;
  4145.  
  4146. .fi
  4147. .Ip "unshift(ARRAY,LIST)" 8 4
  4148. Does the opposite of a
  4149. .IR shift .
  4150. Or the opposite of a
  4151. .IR push ,
  4152. depending on how you look at it.
  4153. Prepends list to the front of the array, and returns the number of elements
  4154. in the new array.
  4155. .nf
  4156.  
  4157.     unshift(ARGV, \'\-e\') unless $ARGV[0] =~ /^\-/;
  4158.  
  4159. .fi
  4160. .Ip "utime(LIST)" 8 2
  4161. .Ip "utime LIST" 8 2
  4162. Changes the access and modification times on each file of a list of files.
  4163. The first two elements of the list must be the NUMERICAL access and
  4164. modification times, in that order.
  4165. Returns the number of files successfully changed.
  4166. The inode modification time of each file is set to the current time.
  4167. Example of a \*(L"touch\*(R" command:
  4168. .nf
  4169.  
  4170. .ne 3
  4171.     #!/usr/bin/perl
  4172.     $now = time;
  4173.     utime $now, $now, @ARGV;
  4174.  
  4175. .fi
  4176. .Ip "values(ASSOC_ARRAY)" 8 6
  4177. .Ip "values ASSOC_ARRAY" 8
  4178. Returns a normal array consisting of all the values of the named associative
  4179. array.
  4180. The values are returned in an apparently random order, but it is the same order
  4181. as either the keys() or each() function would produce on the same array.
  4182. See also keys() and each().
  4183. .Ip "vec(EXPR,OFFSET,BITS)" 8 2
  4184. Treats a string as a vector of unsigned integers, and returns the value
  4185. of the bitfield specified.
  4186. May also be assigned to.
  4187. BITS must be a power of two from 1 to 32.
  4188. .Sp
  4189. Vectors created with vec() can also be manipulated with the logical operators
  4190. |, & and ^,
  4191. which will assume a bit vector operation is desired when both operands are
  4192. strings.
  4193. This interpretation is not enabled unless there is at least one vec() in
  4194. your program, to protect older programs.
  4195. .Sp
  4196. To transform a bit vector into a string or array of 0's and 1's, use these:
  4197. .nf
  4198.  
  4199.     $bits = unpack("b*", $vector);
  4200.     @bits = split(//, unpack("b*", $vector));
  4201.  
  4202. .fi
  4203. If you know the exact length in bits, it can be used in place of the *.
  4204. .Ip "wait" 8 6
  4205. Waits for a child process to terminate and returns the pid of the deceased
  4206. process, or -1 if there are no child processes.
  4207. The status is returned in $?.
  4208. .Ip "waitpid(PID,FLAGS)" 8 6
  4209. Waits for a particular child process to terminate and returns the pid of the deceased
  4210. process, or -1 if there is no such child process.
  4211. The status is returned in $?.
  4212. If you say
  4213. .nf
  4214.  
  4215.     require "sys/wait.h";
  4216.     .\|.\|.
  4217.     waitpid(-1,&WNOHANG);
  4218.  
  4219. .fi
  4220. then you can do a non-blocking wait for any process.  Non-blocking wait
  4221. is only available on machines supporting either the
  4222. .I waitpid (2)
  4223. or
  4224. .I wait4 (2)
  4225. system calls.
  4226. However, waiting for a particular pid with FLAGS of 0 is implemented
  4227. everywhere.  (Perl emulates the system call by remembering the status
  4228. values of processes that have exited but have not been harvested by the
  4229. Perl script yet.)
  4230. .Ip "wantarray" 8 4
  4231. Returns true if the context of the currently executing subroutine
  4232. is looking for an array value.
  4233. Returns false if the context is looking for a scalar.
  4234. .nf
  4235.  
  4236.     return wantarray ? () : undef;
  4237.  
  4238. .fi
  4239. .Ip "warn(LIST)" 8 4
  4240. .Ip "warn LIST" 8
  4241. Produces a message on STDERR just like \*(L"die\*(R", but doesn't exit.
  4242. .Ip "write(FILEHANDLE)" 8 6
  4243. .Ip "write(EXPR)" 8
  4244. .Ip "write" 8
  4245. Writes a formatted record (possibly multi-line) to the specified file,
  4246. using the format associated with that file.
  4247. By default the format for a file is the one having the same name is the
  4248. filehandle, but the format for the current output channel (see
  4249. .IR select )
  4250. may be set explicitly
  4251. by assigning the name of the format to the $~ variable.
  4252. .Sp
  4253. Top of form processing is handled automatically:
  4254. if there is insufficient room on the current page for the formatted 
  4255. record, the page is advanced by writing a form feed,
  4256. a special top-of-page format is used
  4257. to format the new page header, and then the record is written.
  4258. By default the top-of-page format is the name of the filehandle with
  4259. \*(L"_TOP\*(R" appended, but it may be dynamicallly set to the
  4260. format of your choice by assigning the name to the $^ variable while
  4261. the filehandle is selected.
  4262. The number of lines remaining on the current page is in variable $-, which
  4263. can be set to 0 to force a new page.
  4264. .Sp
  4265. If FILEHANDLE is unspecified, output goes to the current default output channel,
  4266. which starts out as
  4267. .I STDOUT
  4268. but may be changed by the
  4269. .I select
  4270. operator.
  4271. If the FILEHANDLE is an EXPR, then the expression is evaluated and the
  4272. resulting string is used to look up the name of the FILEHANDLE at run time.
  4273. For more on formats, see the section on formats later on.
  4274. .Sp
  4275. Note that write is NOT the opposite of read.
  4276. .Sh "Precedence"
  4277. .I Perl
  4278. operators have the following associativity and precedence:
  4279. .nf
  4280.  
  4281. nonassoc\h'|1i'print printf exec system sort reverse
  4282. \h'1.5i'chmod chown kill unlink utime die return
  4283. left\h'|1i',
  4284. right\h'|1i'= += \-= *= etc.
  4285. right\h'|1i'?:
  4286. nonassoc\h'|1i'.\|.
  4287. left\h'|1i'||
  4288. left\h'|1i'&&
  4289. left\h'|1i'| ^
  4290. left\h'|1i'&
  4291. nonassoc\h'|1i'== != <=> eq ne cmp
  4292. nonassoc\h'|1i'< > <= >= lt gt le ge
  4293. nonassoc\h'|1i'chdir exit eval reset sleep rand umask
  4294. nonassoc\h'|1i'\-r \-w \-x etc.
  4295. left\h'|1i'<< >>
  4296. left\h'|1i'+ \- .
  4297. left\h'|1i'* / % x
  4298. left\h'|1i'=~ !~ 
  4299. right\h'|1i'! ~ and unary minus
  4300. right\h'|1i'**
  4301. nonassoc\h'|1i'++ \-\|\-
  4302. left\h'|1i'\*(L'(\*(R'
  4303.  
  4304. .fi
  4305. As mentioned earlier, if any list operator (print, etc.) or
  4306. any unary operator (chdir, etc.)
  4307. is followed by a left parenthesis as the next token on the same line,
  4308. the operator and arguments within parentheses are taken to
  4309. be of highest precedence, just like a normal function call.
  4310. Examples:
  4311. .nf
  4312.  
  4313.     chdir $foo || die;\h'|3i'# (chdir $foo) || die
  4314.     chdir($foo) || die;\h'|3i'# (chdir $foo) || die
  4315.     chdir ($foo) || die;\h'|3i'# (chdir $foo) || die
  4316.     chdir +($foo) || die;\h'|3i'# (chdir $foo) || die
  4317.  
  4318. but, because * is higher precedence than ||:
  4319.  
  4320.     chdir $foo * 20;\h'|3i'# chdir ($foo * 20)
  4321.     chdir($foo) * 20;\h'|3i'# (chdir $foo) * 20
  4322.     chdir ($foo) * 20;\h'|3i'# (chdir $foo) * 20
  4323.     chdir +($foo) * 20;\h'|3i'# chdir ($foo * 20)
  4324.  
  4325.     rand 10 * 20;\h'|3i'# rand (10 * 20)
  4326.     rand(10) * 20;\h'|3i'# (rand 10) * 20
  4327.     rand (10) * 20;\h'|3i'# (rand 10) * 20
  4328.     rand +(10) * 20;\h'|3i'# rand (10 * 20)
  4329.  
  4330. .fi
  4331. In the absence of parentheses,
  4332. the precedence of list operators such as print, sort or chmod is
  4333. either very high or very low depending on whether you look at the left
  4334. side of operator or the right side of it.
  4335. For example, in
  4336. .nf
  4337.  
  4338.     @ary = (1, 3, sort 4, 2);
  4339.     print @ary;        # prints 1324
  4340.  
  4341. .fi
  4342. the commas on the right of the sort are evaluated before the sort, but
  4343. the commas on the left are evaluated after.
  4344. In other words, list operators tend to gobble up all the arguments that
  4345. follow them, and then act like a simple term with regard to the preceding
  4346. expression.
  4347. Note that you have to be careful with parens:
  4348. .nf
  4349.  
  4350. .ne 3
  4351.     # These evaluate exit before doing the print:
  4352.     print($foo, exit);    # Obviously not what you want.
  4353.     print $foo, exit;    # Nor is this.
  4354.  
  4355. .ne 4
  4356.     # These do the print before evaluating exit:
  4357.     (print $foo), exit;    # This is what you want.
  4358.     print($foo), exit;    # Or this.
  4359.     print ($foo), exit;    # Or even this.
  4360.  
  4361. Also note that
  4362.  
  4363.     print ($foo & 255) + 1, "\en";
  4364.  
  4365. .fi
  4366. probably doesn't do what you expect at first glance.
  4367. .Sh "Subroutines"
  4368. A subroutine may be declared as follows:
  4369. .nf
  4370.  
  4371.     sub NAME BLOCK
  4372.  
  4373. .fi
  4374. .PP
  4375. Any arguments passed to the routine come in as array @_,
  4376. that is ($_[0], $_[1], .\|.\|.).
  4377. The array @_ is a local array, but its values are references to the
  4378. actual scalar parameters.
  4379. The return value of the subroutine is the value of the last expression
  4380. evaluated, and can be either an array value or a scalar value.
  4381. Alternately, a return statement may be used to specify the returned value and
  4382. exit the subroutine.
  4383. To create local variables see the
  4384. .I local
  4385. operator.
  4386. .PP
  4387. A subroutine is called using the
  4388. .I do
  4389. operator or the & operator.
  4390. .nf
  4391.  
  4392. .ne 12
  4393. Example:
  4394.  
  4395.     sub MAX {
  4396.         local($max) = pop(@_);
  4397.         foreach $foo (@_) {
  4398.             $max = $foo \|if \|$max < $foo;
  4399.         }
  4400.         $max;
  4401.     }
  4402.  
  4403.     .\|.\|.
  4404.     $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
  4405.  
  4406. .ne 21
  4407. Example:
  4408.  
  4409.     # get a line, combining continuation lines
  4410.     #  that start with whitespace
  4411.     sub get_line {
  4412.         $thisline = $lookahead;
  4413.         line: while ($lookahead = <STDIN>) {
  4414.             if ($lookahead \|=~ \|/\|^[ \^\e\|t]\|/\|) {
  4415.                 $thisline \|.= \|$lookahead;
  4416.             }
  4417.             else {
  4418.                 last line;
  4419.             }
  4420.         }
  4421.         $thisline;
  4422.     }
  4423.  
  4424.     $lookahead = <STDIN>;    # get first line
  4425.     while ($_ = do get_line(\|)) {
  4426.         .\|.\|.
  4427.     }
  4428.  
  4429. .fi
  4430. .nf
  4431. .ne 6
  4432. Use array assignment to a local list to name your formal arguments:
  4433.  
  4434.     sub maybeset {
  4435.         local($key, $value) = @_;
  4436.         $foo{$key} = $value unless $foo{$key};
  4437.     }
  4438.  
  4439. .fi
  4440. This also has the effect of turning call-by-reference into call-by-value,
  4441. since the assignment copies the values.
  4442. .Sp
  4443. Subroutines may be called recursively.
  4444. If a subroutine is called using the & form, the argument list is optional.
  4445. If omitted, no @_ array is set up for the subroutine; the @_ array at the
  4446. time of the call is visible to subroutine instead.
  4447. .nf
  4448.  
  4449.     do foo(1,2,3);        # pass three arguments
  4450.     &foo(1,2,3);        # the same
  4451.  
  4452.     do foo();        # pass a null list
  4453.     &foo();            # the same
  4454.     &foo;            # pass no arguments\*(--more efficient
  4455.  
  4456. .fi
  4457. .Sh "Passing By Reference"
  4458. Sometimes you don't want to pass the value of an array to a subroutine but
  4459. rather the name of it, so that the subroutine can modify the global copy
  4460. of it rather than working with a local copy.
  4461. In perl you can refer to all the objects of a particular name by prefixing
  4462. the name with a star: *foo.
  4463. When evaluated, it produces a scalar value that represents all the objects
  4464. of that name, including any filehandle, format or subroutine.
  4465. When assigned to within a local() operation, it causes the name mentioned
  4466. to refer to whatever * value was assigned to it.
  4467. Example:
  4468. .nf
  4469.  
  4470.     sub doubleary {
  4471.         local(*someary) = @_;
  4472.         foreach $elem (@someary) {
  4473.         $elem *= 2;
  4474.         }
  4475.     }
  4476.     do doubleary(*foo);
  4477.     do doubleary(*bar);
  4478.  
  4479. .fi
  4480. Assignment to *name is currently recommended only inside a local().
  4481. You can actually assign to *name anywhere, but the previous referent of
  4482. *name may be stranded forever.
  4483. This may or may not bother you.
  4484. .Sp
  4485. Note that scalars are already passed by reference, so you can modify scalar
  4486. arguments without using this mechanism by referring explicitly to the $_[nnn]
  4487. in question.
  4488. You can modify all the elements of an array by passing all the elements
  4489. as scalars, but you have to use the * mechanism to push, pop or change the
  4490. size of an array.
  4491. The * mechanism will probably be more efficient in any case.
  4492. .Sp
  4493. Since a *name value contains unprintable binary data, if it is used as
  4494. an argument in a print, or as a %s argument in a printf or sprintf, it
  4495. then has the value '*name', just so it prints out pretty.
  4496. .Sp
  4497. Even if you don't want to modify an array, this mechanism is useful for
  4498. passing multiple arrays in a single LIST, since normally the LIST mechanism
  4499. will merge all the array values so that you can't extract out the
  4500. individual arrays.
  4501. .Sh "Regular Expressions"
  4502. The patterns used in pattern matching are regular expressions such as
  4503. those supplied in the Version 8 regexp routines.
  4504. (In fact, the routines are derived from Henry Spencer's freely redistributable
  4505. reimplementation of the V8 routines.)
  4506. In addition, \ew matches an alphanumeric character (including \*(L"_\*(R") and \eW a nonalphanumeric.
  4507. Word boundaries may be matched by \eb, and non-boundaries by \eB.
  4508. A whitespace character is matched by \es, non-whitespace by \eS.
  4509. A numeric character is matched by \ed, non-numeric by \eD.
  4510. You may use \ew, \es and \ed within character classes.
  4511. Also, \en, \er, \ef, \et and \eNNN have their normal interpretations.
  4512. Within character classes \eb represents backspace rather than a word boundary.
  4513. Alternatives may be separated by |.
  4514. The bracketing construct \|(\ .\|.\|.\ \|) may also be used, in which case \e<digit>
  4515. matches the digit'th substring.
  4516. (Outside of the pattern, always use $ instead of \e in front of the digit.
  4517. The scope of $<digit> (and $\`, $& and $\')
  4518. extends to the end of the enclosing BLOCK or eval string, or to
  4519. the next pattern match with subexpressions.
  4520. The \e<digit> notation sometimes works outside the current pattern, but should
  4521. not be relied upon.)
  4522. You may have as many parentheses as you wish.  If you have more than 9
  4523. substrings, the variables $10, $11, ... refer to the corresponding
  4524. substring.  Within the pattern, \e10, \e11,
  4525. etc. refer back to substrings if there have been at least that many left parens
  4526. before the backreference.  Otherwise (for backward compatibilty) \e10
  4527. is the same as \e010, a backspace,
  4528. and \e11 the same as \e011, a tab.
  4529. And so on.
  4530. (\e1 through \e9 are always backreferences.)
  4531. .PP
  4532. $+ returns whatever the last bracket match matched.
  4533. $& returns the entire matched string.
  4534. ($0 used to return the same thing, but not any more.)
  4535. $\` returns everything before the matched string.
  4536. $\' returns everything after the matched string.
  4537. Examples:
  4538. .nf
  4539.     
  4540.     s/\|^\|([^ \|]*\|) \|*([^ \|]*\|)\|/\|$2 $1\|/;    # swap first two words
  4541.  
  4542. .ne 5
  4543.     if (/\|Time: \|(.\|.\|):\|(.\|.\|):\|(.\|.\|)\|/\|) {
  4544.         $hours = $1;
  4545.         $minutes = $2;
  4546.         $seconds = $3;
  4547.     }
  4548.  
  4549. .fi
  4550. By default, the ^ character is only guaranteed to match at the beginning
  4551. of the string,
  4552. the $ character only at the end (or before the newline at the end)
  4553. and
  4554. .I perl
  4555. does certain optimizations with the assumption that the string contains
  4556. only one line.
  4557. The behavior of ^ and $ on embedded newlines will be inconsistent.
  4558. You may, however, wish to treat a string as a multi-line buffer, such that
  4559. the ^ will match after any newline within the string, and $ will match
  4560. before any newline.
  4561. At the cost of a little more overhead, you can do this by setting the variable
  4562. $* to 1.
  4563. Setting it back to 0 makes
  4564. .I perl
  4565. revert to its old behavior.
  4566. .PP
  4567. To facilitate multi-line substitutions, the . character never matches a newline
  4568. (even when $* is 0).
  4569. In particular, the following leaves a newline on the $_ string:
  4570. .nf
  4571.  
  4572.     $_ = <STDIN>;
  4573.     s/.*(some_string).*/$1/;
  4574.  
  4575. If the newline is unwanted, try one of
  4576.  
  4577.     s/.*(some_string).*\en/$1/;
  4578.     s/.*(some_string)[^\e000]*/$1/;
  4579.     s/.*(some_string)(.|\en)*/$1/;
  4580.     chop; s/.*(some_string).*/$1/;
  4581.     /(some_string)/ && ($_ = $1);
  4582.  
  4583. .fi
  4584. Any item of a regular expression may be followed with digits in curly brackets
  4585. of the form {n,m}, where n gives the minimum number of times to match the item
  4586. and m gives the maximum.
  4587. The form {n} is equivalent to {n,n} and matches exactly n times.
  4588. The form {n,} matches n or more times.
  4589. (If a curly bracket occurs in any other context, it is treated as a regular
  4590. character.)
  4591. The * modifier is equivalent to {0,}, the + modifier to {1,} and the ? modifier
  4592. to {0,1}.
  4593. There is no limit to the size of n or m, but large numbers will chew up
  4594. more memory.
  4595. .Sp
  4596. You will note that all backslashed metacharacters in
  4597. .I perl
  4598. are alphanumeric,
  4599. such as \eb, \ew, \en.
  4600. Unlike some other regular expression languages, there are no backslashed
  4601. symbols that aren't alphanumeric.
  4602. So anything that looks like \e\e, \e(, \e), \e<, \e>, \e{, or \e} is always
  4603. interpreted as a literal character, not a metacharacter.
  4604. This makes it simple to quote a string that you want to use for a pattern
  4605. but that you are afraid might contain metacharacters.
  4606. Simply quote all the non-alphanumeric characters:
  4607. .nf
  4608.  
  4609.     $pattern =~ s/(\eW)/\e\e$1/g;
  4610.  
  4611. .fi
  4612. .Sh "Formats"
  4613. Output record formats for use with the
  4614. .I write
  4615. operator may declared as follows:
  4616. .nf
  4617.  
  4618. .ne 3
  4619.     format NAME =
  4620.     FORMLIST
  4621.     .
  4622.  
  4623. .fi
  4624. If name is omitted, format \*(L"STDOUT\*(R" is defined.
  4625. FORMLIST consists of a sequence of lines, each of which may be of one of three
  4626. types:
  4627. .Ip 1. 4
  4628. A comment.
  4629. .Ip 2. 4
  4630. A \*(L"picture\*(R" line giving the format for one output line.
  4631. .Ip 3. 4
  4632. An argument line supplying values to plug into a picture line.
  4633. .PP
  4634. Picture lines are printed exactly as they look, except for certain fields
  4635. that substitute values into the line.
  4636. Each picture field starts with either @ or ^.
  4637. The @ field (not to be confused with the array marker @) is the normal
  4638. case; ^ fields are used
  4639. to do rudimentary multi-line text block filling.
  4640. The length of the field is supplied by padding out the field
  4641. with multiple <, >, or | characters to specify, respectively, left justification,
  4642. right justification, or centering.
  4643. As an alternate form of right justification,
  4644. you may also use # characters (with an optional .) to specify a numeric field.
  4645. (Use of ^ instead of @ causes the field to be blanked if undefined.)
  4646. If any of the values supplied for these fields contains a newline, only
  4647. the text up to the newline is printed.
  4648. The special field @* can be used for printing multi-line values.
  4649. It should appear by itself on a line.
  4650. .PP
  4651. The values are specified on the following line, in the same order as
  4652. the picture fields.
  4653. The values should be separated by commas.
  4654. .PP
  4655. Picture fields that begin with ^ rather than @ are treated specially.
  4656. The value supplied must be a scalar variable name which contains a text
  4657. string.
  4658. .I Perl
  4659. puts as much text as it can into the field, and then chops off the front
  4660. of the string so that the next time the variable is referenced,
  4661. more of the text can be printed.
  4662. Normally you would use a sequence of fields in a vertical stack to print
  4663. out a block of text.
  4664. If you like, you can end the final field with .\|.\|., which will appear in the
  4665. output if the text was too long to appear in its entirety.
  4666. You can change which characters are legal to break on by changing the
  4667. variable $: to a list of the desired characters.
  4668. .PP
  4669. Since use of ^ fields can produce variable length records if the text to be
  4670. formatted is short, you can suppress blank lines by putting the tilde (~)
  4671. character anywhere in the line.
  4672. (Normally you should put it in the front if possible, for visibility.)
  4673. The tilde will be translated to a space upon output.
  4674. If you put a second tilde contiguous to the first, the line will be repeated
  4675. until all the fields on the line are exhausted.
  4676. (If you use a field of the @ variety, the expression you supply had better
  4677. not give the same value every time forever!)
  4678. .PP
  4679. Examples:
  4680. .nf
  4681. .lg 0
  4682. .cs R 25
  4683. .ft C
  4684.  
  4685. .ne 10
  4686. # a report on the /etc/passwd file
  4687. format STDOUT_TOP =
  4688. \&                        Passwd File
  4689. Name                Login    Office   Uid   Gid Home
  4690. ------------------------------------------------------------------
  4691. \&.
  4692. format STDOUT =
  4693. @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
  4694. $name,              $login,  $office,$uid,$gid, $home
  4695. \&.
  4696.  
  4697. .ne 29
  4698. # a report from a bug report form
  4699. format STDOUT_TOP =
  4700. \&                        Bug Reports
  4701. @<<<<<<<<<<<<<<<<<<<<<<<     @|||         @>>>>>>>>>>>>>>>>>>>>>>>
  4702. $system,                      $%,         $date
  4703. ------------------------------------------------------------------
  4704. \&.
  4705. format STDOUT =
  4706. Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4707. \&         $subject
  4708. Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4709. \&       $index,                       $description
  4710. Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4711. \&          $priority,        $date,   $description
  4712. From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4713. \&      $from,                         $description
  4714. Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4715. \&             $programmer,            $description
  4716. \&~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4717. \&                                     $description
  4718. \&~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4719. \&                                     $description
  4720. \&~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4721. \&                                     $description
  4722. \&~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4723. \&                                     $description
  4724. \&~                                    ^<<<<<<<<<<<<<<<<<<<<<<<...
  4725. \&                                     $description
  4726. \&.
  4727.  
  4728. .ft R
  4729. .cs R
  4730. .lg
  4731. .fi
  4732. It is possible to intermix prints with writes on the same output channel,
  4733. but you'll have to handle $\- (lines left on the page) yourself.
  4734. .PP
  4735. If you are printing lots of fields that are usually blank, you should consider
  4736. using the reset operator between records.
  4737. Not only is it more efficient, but it can prevent the bug of adding another
  4738. field and forgetting to zero it.
  4739. .Sh "Interprocess Communication"
  4740. The IPC facilities of perl are built on the Berkeley socket mechanism.
  4741. If you don't have sockets, you can ignore this section.
  4742. The calls have the same names as the corresponding system calls,
  4743. but the arguments tend to differ, for two reasons.
  4744. First, perl file handles work differently than C file descriptors.
  4745. Second, perl already knows the length of its strings, so you don't need
  4746. to pass that information.
  4747. Here is a sample client (untested):
  4748. .nf
  4749.  
  4750.     ($them,$port) = @ARGV;
  4751.     $port = 2345 unless $port;
  4752.     $them = 'localhost' unless $them;
  4753.  
  4754.     $SIG{'INT'} = 'dokill';
  4755.     sub dokill { kill 9,$child if $child; }
  4756.  
  4757.     require 'sys/socket.ph';
  4758.  
  4759.     $sockaddr = 'S n a4 x8';
  4760.     chop($hostname = `hostname`);
  4761.  
  4762.     ($name, $aliases, $proto) = getprotobyname('tcp');
  4763.     ($name, $aliases, $port) = getservbyname($port, 'tcp')
  4764.         unless $port =~ /^\ed+$/;
  4765. .ie t \{\
  4766.     ($name, $aliases, $type, $len, $thisaddr) = gethostbyname($hostname);
  4767. 'br\}
  4768. .el \{\
  4769.     ($name, $aliases, $type, $len, $thisaddr) =
  4770.                     gethostbyname($hostname);
  4771. 'br\}
  4772.     ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
  4773.  
  4774.     $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
  4775.     $that = pack($sockaddr, &AF_INET, $port, $thataddr);
  4776.  
  4777.     socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  4778.     bind(S, $this) || die "bind: $!";
  4779.     connect(S, $that) || die "connect: $!";
  4780.  
  4781.     select(S); $| = 1; select(stdout);
  4782.  
  4783.     if ($child = fork) {
  4784.         while (<>) {
  4785.             print S;
  4786.         }
  4787.         sleep 3;
  4788.         do dokill();
  4789.     }
  4790.     else {
  4791.         while (<S>) {
  4792.             print;
  4793.         }
  4794.     }
  4795.  
  4796. .fi
  4797. And here's a server:
  4798. .nf
  4799.  
  4800.     ($port) = @ARGV;
  4801.     $port = 2345 unless $port;
  4802.  
  4803.     require 'sys/socket.ph';
  4804.  
  4805.     $sockaddr = 'S n a4 x8';
  4806.  
  4807.     ($name, $aliases, $proto) = getprotobyname('tcp');
  4808.     ($name, $aliases, $port) = getservbyname($port, 'tcp')
  4809.         unless $port =~ /^\ed+$/;
  4810.  
  4811.     $this = pack($sockaddr, &AF_INET, $port, "\e0\e0\e0\e0");
  4812.  
  4813.     select(NS); $| = 1; select(stdout);
  4814.  
  4815.     socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  4816.     bind(S, $this) || die "bind: $!";
  4817.     listen(S, 5) || die "connect: $!";
  4818.  
  4819.     select(S); $| = 1; select(stdout);
  4820.  
  4821.     for (;;) {
  4822.         print "Listening again\en";
  4823.         ($addr = accept(NS,S)) || die $!;
  4824.         print "accept ok\en";
  4825.  
  4826.         ($af,$port,$inetaddr) = unpack($sockaddr,$addr);
  4827.         @inetaddr = unpack('C4',$inetaddr);
  4828.         print "$af $port @inetaddr\en";
  4829.  
  4830.         while (<NS>) {
  4831.             print;
  4832.             print NS;
  4833.         }
  4834.     }
  4835.  
  4836. .fi
  4837. .Sh "Predefined Names"
  4838. The following names have special meaning to
  4839. .IR perl .
  4840. I could have used alphabetic symbols for some of these, but I didn't want
  4841. to take the chance that someone would say reset \*(L"a\-zA\-Z\*(R" and wipe them all
  4842. out.
  4843. You'll just have to suffer along with these silly symbols.
  4844. Most of them have reasonable mnemonics, or analogues in one of the shells.
  4845. .Ip $_ 8
  4846. The default input and pattern-searching space.
  4847. The following pairs are equivalent:
  4848. .nf
  4849.  
  4850. .ne 2
  4851.     while (<>) {\|.\|.\|.    # only equivalent in while!
  4852.     while ($_ = <>) {\|.\|.\|.
  4853.  
  4854. .ne 2
  4855.     /\|^Subject:/
  4856.     $_ \|=~ \|/\|^Subject:/
  4857.  
  4858. .ne 2
  4859.     y/a\-z/A\-Z/
  4860.     $_ =~ y/a\-z/A\-Z/
  4861.  
  4862. .ne 2
  4863.     chop
  4864.     chop($_)
  4865.  
  4866. .fi 
  4867. (Mnemonic: underline is understood in certain operations.)
  4868. .Ip $. 8
  4869. The current input line number of the last filehandle that was read.
  4870. Readonly.
  4871. Remember that only an explicit close on the filehandle resets the line number.
  4872. Since <> never does an explicit close, line numbers increase across ARGV files
  4873. (but see examples under eof).
  4874. (Mnemonic: many programs use . to mean the current line number.)
  4875. .Ip $/ 8
  4876. The input record separator, newline by default.
  4877. Works like
  4878. .IR awk 's
  4879. RS variable, including treating blank lines as delimiters
  4880. if set to the null string.
  4881. You may set it to a multicharacter string to match a multi-character
  4882. delimiter.
  4883. (Mnemonic: / is used to delimit line boundaries when quoting poetry.)
  4884. .Ip $, 8
  4885. The output field separator for the print operator.
  4886. Ordinarily the print operator simply prints out the comma separated fields
  4887. you specify.
  4888. In order to get behavior more like
  4889. .IR awk ,
  4890. set this variable as you would set
  4891. .IR awk 's
  4892. OFS variable to specify what is printed between fields.
  4893. (Mnemonic: what is printed when there is a , in your print statement.)
  4894. .Ip $"" 8
  4895. This is like $, except that it applies to array values interpolated into
  4896. a double-quoted string (or similar interpreted string).
  4897. Default is a space.
  4898. (Mnemonic: obvious, I think.)
  4899. .Ip $\e 8
  4900. The output record separator for the print operator.
  4901. Ordinarily the print operator simply prints out the comma separated fields
  4902. you specify, with no trailing newline or record separator assumed.
  4903. In order to get behavior more like
  4904. .IR awk ,
  4905. set this variable as you would set
  4906. .IR awk 's
  4907. ORS variable to specify what is printed at the end of the print.
  4908. (Mnemonic: you set $\e instead of adding \en at the end of the print.
  4909. Also, it's just like /, but it's what you get \*(L"back\*(R" from
  4910. .IR perl .)
  4911. .Ip $# 8
  4912. The output format for printed numbers.
  4913. This variable is a half-hearted attempt to emulate
  4914. .IR awk 's
  4915. OFMT variable.
  4916. There are times, however, when
  4917. .I awk
  4918. and
  4919. .I perl
  4920. have differing notions of what
  4921. is in fact numeric.
  4922. Also, the initial value is %.20g rather than %.6g, so you need to set $#
  4923. explicitly to get
  4924. .IR awk 's
  4925. value.
  4926. (Mnemonic: # is the number sign.)
  4927. .Ip $% 8
  4928. The current page number of the currently selected output channel.
  4929. (Mnemonic: % is page number in nroff.)
  4930. .Ip $= 8
  4931. The current page length (printable lines) of the currently selected output
  4932. channel.
  4933. Default is 60.
  4934. (Mnemonic: = has horizontal lines.)
  4935. .Ip $\- 8
  4936. The number of lines left on the page of the currently selected output channel.
  4937. (Mnemonic: lines_on_page \- lines_printed.)
  4938. .Ip $~ 8
  4939. The name of the current report format for the currently selected output
  4940. channel.
  4941. Default is name of the filehandle.
  4942. (Mnemonic: brother to $^.)
  4943. .Ip $^ 8
  4944. The name of the current top-of-page format for the currently selected output
  4945. channel.
  4946. Default is name of the filehandle with \*(L"_TOP\*(R" appended.
  4947. (Mnemonic: points to top of page.)
  4948. .Ip $| 8
  4949. If set to nonzero, forces a flush after every write or print on the currently
  4950. selected output channel.
  4951. Default is 0.
  4952. Note that
  4953. .I STDOUT
  4954. will typically be line buffered if output is to the
  4955. terminal and block buffered otherwise.
  4956. Setting this variable is useful primarily when you are outputting to a pipe,
  4957. such as when you are running a
  4958. .I perl
  4959. script under rsh and want to see the
  4960. output as it's happening.
  4961. (Mnemonic: when you want your pipes to be piping hot.)
  4962. .Ip $$ 8
  4963. The process number of the
  4964. .I perl
  4965. running this script.
  4966. (Mnemonic: same as shells.)
  4967. .Ip $? 8
  4968. The status returned by the last pipe close, backtick (\`\`) command or
  4969. .I system
  4970. operator.
  4971. Note that this is the status word returned by the wait() system
  4972. call, so the exit value of the subprocess is actually ($? >> 8).
  4973. $? & 255 gives which signal, if any, the process died from, and whether
  4974. there was a core dump.
  4975. (Mnemonic: similar to sh and ksh.)
  4976. .Ip $& 8 4
  4977. The string matched by the last pattern match (not counting any matches hidden
  4978. within a BLOCK or eval enclosed by the current BLOCK).
  4979. (Mnemonic: like & in some editors.)
  4980. .Ip $\` 8 4
  4981. The string preceding whatever was matched by the last pattern match
  4982. (not counting any matches hidden within a BLOCK or eval enclosed by the current
  4983. BLOCK).
  4984. (Mnemonic: \` often precedes a quoted string.)
  4985. .Ip $\' 8 4
  4986. The string following whatever was matched by the last pattern match
  4987. (not counting any matches hidden within a BLOCK or eval enclosed by the current
  4988. BLOCK).
  4989. (Mnemonic: \' often follows a quoted string.)
  4990. Example:
  4991. .nf
  4992.  
  4993. .ne 3
  4994.     $_ = \'abcdefghi\';
  4995.     /def/;
  4996.     print "$\`:$&:$\'\en";      # prints abc:def:ghi
  4997.  
  4998. .fi
  4999. .Ip $+ 8 4
  5000. The last bracket matched by the last search pattern.
  5001. This is useful if you don't know which of a set of alternative patterns
  5002. matched.
  5003. For example:
  5004. .nf
  5005.  
  5006.     /Version: \|(.*\|)|Revision: \|(.*\|)\|/ \|&& \|($rev = $+);
  5007.  
  5008. .fi
  5009. (Mnemonic: be positive and forward looking.)
  5010. .Ip $* 8 2
  5011. Set to 1 to do multiline matching within a string, 0 to tell
  5012. .I perl
  5013. that it can assume that strings contain a single line, for the purpose
  5014. of optimizing pattern matches.
  5015. Pattern matches on strings containing multiple newlines can produce confusing
  5016. results when $* is 0.
  5017. Default is 0.
  5018. (Mnemonic: * matches multiple things.)
  5019. Note that this variable only influences the interpretation of ^ and $.
  5020. A literal newline can be searched for even when $* == 0.
  5021. .Ip $0 8
  5022. Contains the name of the file containing the
  5023. .I perl
  5024. script being executed.
  5025. Assigning to $0 modifies the argument area that the ps(1) program sees.
  5026. (Mnemonic: same as sh and ksh.)
  5027. .Ip $<digit> 8
  5028. Contains the subpattern from the corresponding set of parentheses in the last
  5029. pattern matched, not counting patterns matched in nested blocks that have
  5030. been exited already.
  5031. (Mnemonic: like \edigit.)
  5032. .Ip $[ 8 2
  5033. The index of the first element in an array, and of the first character in
  5034. a substring.
  5035. Default is 0, but you could set it to 1 to make
  5036. .I perl
  5037. behave more like
  5038. .I awk
  5039. (or Fortran)
  5040. when subscripting and when evaluating the index() and substr() functions.
  5041. (Mnemonic: [ begins subscripts.)
  5042. .Ip $] 8 2
  5043. The string printed out when you say \*(L"perl -v\*(R".
  5044. It can be used to determine at the beginning of a script whether the perl
  5045. interpreter executing the script is in the right range of versions.
  5046. If used in a numeric context, returns the version + patchlevel / 1000.
  5047. Example:
  5048. .nf
  5049.  
  5050. .ne 8
  5051.     # see if getc is available
  5052.         ($version,$patchlevel) =
  5053.          $] =~ /(\ed+\e.\ed+).*\enPatch level: (\ed+)/;
  5054.         print STDERR "(No filename completion available.)\en"
  5055.          if $version * 1000 + $patchlevel < 2016;
  5056.  
  5057. or, used numerically,
  5058.  
  5059.     warn "No checksumming!\en" if $] < 3.019;
  5060.  
  5061. .fi
  5062. (Mnemonic: Is this version of perl in the right bracket?)
  5063. .Ip $; 8 2
  5064. The subscript separator for multi-dimensional array emulation.
  5065. If you refer to an associative array element as
  5066. .nf
  5067.     $foo{$a,$b,$c}
  5068.  
  5069. it really means
  5070.  
  5071.     $foo{join($;, $a, $b, $c)}
  5072.  
  5073. But don't put
  5074.  
  5075.     @foo{$a,$b,$c}        # a slice\*(--note the @
  5076.  
  5077. which means
  5078.  
  5079.     ($foo{$a},$foo{$b},$foo{$c})
  5080.  
  5081. .fi
  5082. Default is "\e034", the same as SUBSEP in
  5083. .IR awk .
  5084. Note that if your keys contain binary data there might not be any safe
  5085. value for $;.
  5086. (Mnemonic: comma (the syntactic subscript separator) is a semi-semicolon.
  5087. Yeah, I know, it's pretty lame, but $, is already taken for something more
  5088. important.)
  5089. .Ip $! 8 2
  5090. If used in a numeric context, yields the current value of errno, with all the
  5091. usual caveats.
  5092. (This means that you shouldn't depend on the value of $! to be anything
  5093. in particular unless you've gotten a specific error return indicating a
  5094. system error.)
  5095. If used in a string context, yields the corresponding system error string.
  5096. You can assign to $! in order to set errno
  5097. if, for instance, you want $! to return the string for error n, or you want
  5098. to set the exit value for the die operator.
  5099. (Mnemonic: What just went bang?)
  5100. .Ip $@ 8 2
  5101. The perl syntax error message from the last eval command.
  5102. If null, the last eval parsed and executed correctly (although the operations
  5103. you invoked may have failed in the normal fashion).
  5104. (Mnemonic: Where was the syntax error \*(L"at\*(R"?)
  5105. .Ip $< 8 2
  5106. The real uid of this process.
  5107. (Mnemonic: it's the uid you came FROM, if you're running setuid.)
  5108. .Ip $> 8 2
  5109. The effective uid of this process.
  5110. Example:
  5111. .nf
  5112.  
  5113. .ne 2
  5114.     $< = $>;    # set real uid to the effective uid
  5115.     ($<,$>) = ($>,$<);    # swap real and effective uid
  5116.  
  5117. .fi
  5118. (Mnemonic: it's the uid you went TO, if you're running setuid.)
  5119. Note: $< and $> can only be swapped on machines supporting setreuid().
  5120. .Ip $( 8 2
  5121. The real gid of this process.
  5122. If you are on a machine that supports membership in multiple groups
  5123. simultaneously, gives a space separated list of groups you are in.
  5124. The first number is the one returned by getgid(), and the subsequent ones
  5125. by getgroups(), one of which may be the same as the first number.
  5126. (Mnemonic: parentheses are used to GROUP things.
  5127. The real gid is the group you LEFT, if you're running setgid.)
  5128. .Ip $) 8 2
  5129. The effective gid of this process.
  5130. If you are on a machine that supports membership in multiple groups
  5131. simultaneously, gives a space separated list of groups you are in.
  5132. The first number is the one returned by getegid(), and the subsequent ones
  5133. by getgroups(), one of which may be the same as the first number.
  5134. (Mnemonic: parentheses are used to GROUP things.
  5135. The effective gid is the group that's RIGHT for you, if you're running setgid.)
  5136. .Sp
  5137. Note: $<, $>, $( and $) can only be set on machines that support the
  5138. corresponding set[re][ug]id() routine.
  5139. $( and $) can only be swapped on machines supporting setregid().
  5140. .Ip $: 8 2
  5141. The current set of characters after which a string may be broken to
  5142. fill continuation fields (starting with ^) in a format.
  5143. Default is "\ \en-", to break on whitespace or hyphens.
  5144. (Mnemonic: a \*(L"colon\*(R" in poetry is a part of a line.)
  5145. .Ip $^D 8 2
  5146. The current value of the debugging flags.
  5147. (Mnemonic: value of
  5148. .B \-D
  5149. switch.)
  5150. .Ip $^F 8 2
  5151. The maximum system file descriptor, ordinarily 2.  System file descriptors
  5152. are passed to subprocesses, while higher file descriptors are not.
  5153. During an open, system file descriptors are preserved even if the open
  5154. fails.  Ordinary file descriptors are closed before the open is attempted.
  5155. .Ip $^I 8 2
  5156. The current value of the inplace-edit extension.
  5157. Use undef to disable inplace editing.
  5158. (Mnemonic: value of
  5159. .B \-i
  5160. switch.)
  5161. .Ip $^P 8 2
  5162. The internal flag that the debugger clears so that it doesn't
  5163. debug itself.  You could conceivable disable debugging yourself
  5164. by clearing it.
  5165. .Ip $^T 8 2
  5166. The time at which the script began running, in seconds since the epoch.
  5167. The values returned by the
  5168. .B \-M ,
  5169. .B \-A
  5170. and
  5171. .B \-C
  5172. filetests are based on this value.
  5173. .Ip $^W 8 2
  5174. The current value of the warning switch.
  5175. (Mnemonic: related to the
  5176. .B \-w
  5177. switch.)
  5178. .Ip $^X 8 2
  5179. The name that Perl itself was executed as, from argv[0].
  5180. .Ip $ARGV 8 3
  5181. contains the name of the current file when reading from <>.
  5182. .Ip @ARGV 8 3
  5183. The array ARGV contains the command line arguments intended for the script.
  5184. Note that $#ARGV is the generally number of arguments minus one, since
  5185. $ARGV[0] is the first argument, NOT the command name.
  5186. See $0 for the command name.
  5187. .Ip @INC 8 3
  5188. The array INC contains the list of places to look for
  5189. .I perl
  5190. scripts to be
  5191. evaluated by the \*(L"do EXPR\*(R" command or the \*(L"require\*(R" command.
  5192. It initially consists of the arguments to any
  5193. .B \-I
  5194. command line switches, followed
  5195. by the default
  5196. .I perl
  5197. library, probably \*(L"/usr/local/lib/perl\*(R",
  5198. followed by \*(L".\*(R", to represent the current directory.
  5199. .Ip %INC 8 3
  5200. The associative array INC contains entries for each filename that has
  5201. been included via \*(L"do\*(R" or \*(L"require\*(R".
  5202. The key is the filename you specified, and the value is the location of
  5203. the file actually found.
  5204. The \*(L"require\*(R" command uses this array to determine whether
  5205. a given file has already been included.
  5206. .Ip $ENV{expr} 8 2
  5207. The associative array ENV contains your current environment.
  5208. Setting a value in ENV changes the environment for child processes.
  5209. .Ip $SIG{expr} 8 2
  5210. The associative array SIG is used to set signal handlers for various signals.
  5211. Example:
  5212. .nf
  5213.  
  5214. .ne 12
  5215.     sub handler {    # 1st argument is signal name
  5216.         local($sig) = @_;
  5217.         print "Caught a SIG$sig\-\|\-shutting down\en";
  5218.         close(LOG);
  5219.         exit(0);
  5220.     }
  5221.  
  5222.     $SIG{\'INT\'} = \'handler\';
  5223.     $SIG{\'QUIT\'} = \'handler\';
  5224.     .\|.\|.
  5225.     $SIG{\'INT\'} = \'DEFAULT\';    # restore default action
  5226.     $SIG{\'QUIT\'} = \'IGNORE\';    # ignore SIGQUIT
  5227.  
  5228. .fi
  5229. The SIG array only contains values for the signals actually set within
  5230. the perl script.
  5231. .Sh "Packages"
  5232. Perl provides a mechanism for alternate namespaces to protect packages from
  5233. stomping on each others variables.
  5234. By default, a perl script starts compiling into the package known as \*(L"main\*(R".
  5235. By use of the
  5236. .I package
  5237. declaration, you can switch namespaces.
  5238. The scope of the package declaration is from the declaration itself to the end
  5239. of the enclosing block (the same scope as the local() operator).
  5240. Typically it would be the first declaration in a file to be included by
  5241. the \*(L"require\*(R" operator.
  5242. You can switch into a package in more than one place; it merely influences
  5243. which symbol table is used by the compiler for the rest of that block.
  5244. You can refer to variables and filehandles in other packages by prefixing
  5245. the identifier with the package name and a single quote.
  5246. If the package name is null, the \*(L"main\*(R" package as assumed.
  5247. .PP
  5248. Only identifiers starting with letters are stored in the packages symbol
  5249. table.
  5250. All other symbols are kept in package \*(L"main\*(R".
  5251. In addition, the identifiers STDIN, STDOUT, STDERR, ARGV, ARGVOUT, ENV, INC
  5252. and SIG are forced to be in package \*(L"main\*(R", even when used for
  5253. other purposes than their built-in one.
  5254. Note also that, if you have a package called \*(L"m\*(R", \*(L"s\*(R"
  5255. or \*(L"y\*(R", the you can't use the qualified form of an identifier since it
  5256. will be interpreted instead as a pattern match, a substitution
  5257. or a translation.
  5258. .PP
  5259. Eval'ed strings are compiled in the package in which the eval was compiled
  5260. in.
  5261. (Assignments to $SIG{}, however, assume the signal handler specified is in the
  5262. main package.
  5263. Qualify the signal handler name if you wish to have a signal handler in
  5264. a package.)
  5265. For an example, examine perldb.pl in the perl library.
  5266. It initially switches to the DB package so that the debugger doesn't interfere
  5267. with variables in the script you are trying to debug.
  5268. At various points, however, it temporarily switches back to the main package
  5269. to evaluate various expressions in the context of the main package.
  5270. .PP
  5271. The symbol table for a package happens to be stored in the associative array
  5272. of that name prepended with an underscore.
  5273. The value in each entry of the associative array is
  5274. what you are referring to when you use the *name notation.
  5275. In fact, the following have the same effect (in package main, anyway),
  5276. though the first is more
  5277. efficient because it does the symbol table lookups at compile time:
  5278. .nf
  5279.  
  5280. .ne 2
  5281.     local(*foo) = *bar;
  5282.     local($_main{'foo'}) = $_main{'bar'};
  5283.  
  5284. .fi
  5285. You can use this to print out all the variables in a package, for instance.
  5286. Here is dumpvar.pl from the perl library:
  5287. .nf
  5288. .ne 11
  5289.     package dumpvar;
  5290.  
  5291.     sub main'dumpvar {
  5292.     \&    ($package) = @_;
  5293.     \&    local(*stab) = eval("*_$package");
  5294.     \&    while (($key,$val) = each(%stab)) {
  5295.     \&        {
  5296.     \&            local(*entry) = $val;
  5297.     \&            if (defined $entry) {
  5298.     \&                print "\e$$key = '$entry'\en";
  5299.     \&            }
  5300. .ne 7
  5301.     \&            if (defined @entry) {
  5302.     \&                print "\e@$key = (\en";
  5303.     \&                foreach $num ($[ .. $#entry) {
  5304.     \&                    print "  $num\et'",$entry[$num],"'\en";
  5305.     \&                }
  5306.     \&                print ")\en";
  5307.     \&            }
  5308. .ne 10
  5309.     \&            if ($key ne "_$package" && defined %entry) {
  5310.     \&                print "\e%$key = (\en";
  5311.     \&                foreach $key (sort keys(%entry)) {
  5312.     \&                    print "  $key\et'",$entry{$key},"'\en";
  5313.     \&                }
  5314.     \&                print ")\en";
  5315.     \&            }
  5316.     \&        }
  5317.     \&    }
  5318.     }
  5319.  
  5320. .fi
  5321. Note that, even though the subroutine is compiled in package dumpvar, the
  5322. name of the subroutine is qualified so that its name is inserted into package
  5323. \*(L"main\*(R".
  5324. .Sh "Style"
  5325. Each programmer will, of course, have his or her own preferences in regards
  5326. to formatting, but there are some general guidelines that will make your
  5327. programs easier to read.
  5328. .Ip 1. 4 4
  5329. Just because you CAN do something a particular way doesn't mean that
  5330. you SHOULD do it that way.
  5331. .I Perl
  5332. is designed to give you several ways to do anything, so consider picking
  5333. the most readable one.
  5334. For instance
  5335.  
  5336.     open(FOO,$foo) || die "Can't open $foo: $!";
  5337.  
  5338. is better than
  5339.  
  5340.     die "Can't open $foo: $!" unless open(FOO,$foo);
  5341.  
  5342. because the second way hides the main point of the statement in a
  5343. modifier.
  5344. On the other hand
  5345.  
  5346.     print "Starting analysis\en" if $verbose;
  5347.  
  5348. is better than
  5349.  
  5350.     $verbose && print "Starting analysis\en";
  5351.  
  5352. since the main point isn't whether the user typed -v or not.
  5353. .Sp
  5354. Similarly, just because an operator lets you assume default arguments
  5355. doesn't mean that you have to make use of the defaults.
  5356. The defaults are there for lazy systems programmers writing one-shot
  5357. programs.
  5358. If you want your program to be readable, consider supplying the argument.
  5359. .Sp
  5360. Along the same lines, just because you
  5361. .I can
  5362. omit parentheses in many places doesn't mean that you ought to:
  5363. .nf
  5364.  
  5365.     return print reverse sort num values array;
  5366.     return print(reverse(sort num (values(%array))));
  5367.  
  5368. .fi
  5369. When in doubt, parenthesize.
  5370. At the very least it will let some poor schmuck bounce on the % key in vi.
  5371. .Sp
  5372. Even if you aren't in doubt, consider the mental welfare of the person who
  5373. has to maintain the code after you, and who will probably put parens in
  5374. the wrong place.
  5375. .Ip 2. 4 4
  5376. Don't go through silly contortions to exit a loop at the top or the
  5377. bottom, when
  5378. .I perl
  5379. provides the "last" operator so you can exit in the middle.
  5380. Just outdent it a little to make it more visible:
  5381. .nf
  5382.  
  5383. .ne 7
  5384.     line:
  5385.     for (;;) {
  5386.         statements;
  5387.     last line if $foo;
  5388.         next line if /^#/;
  5389.         statements;
  5390.     }
  5391.  
  5392. .fi
  5393. .Ip 3. 4 4
  5394. Don't be afraid to use loop labels\*(--they're there to enhance readability as
  5395. well as to allow multi-level loop breaks.
  5396. See last example.
  5397. .Ip 4. 4 4
  5398. For portability, when using features that may not be implemented on every
  5399. machine, test the construct in an eval to see if it fails.
  5400. If you know what version or patchlevel a particular feature was implemented,
  5401. you can test $] to see if it will be there.
  5402. .Ip 5. 4 4
  5403. Choose mnemonic identifiers.
  5404. .Ip 6. 4 4
  5405. Be consistent.
  5406. .Sh "Debugging"
  5407. If you invoke
  5408. .I perl
  5409. with a
  5410. .B \-d
  5411. switch, your script will be run under a debugging monitor.
  5412. It will halt before the first executable statement and ask you for a
  5413. command, such as:
  5414. .Ip "h" 12 4
  5415. Prints out a help message.
  5416. .Ip "T" 12 4
  5417. Stack trace.
  5418. .Ip "s" 12 4
  5419. Single step.
  5420. Executes until it reaches the beginning of another statement.
  5421. .Ip "n" 12 4
  5422. Next.
  5423. Executes over subroutine calls, until it reaches the beginning of the 
  5424. next statement.
  5425. .Ip "f" 12 4
  5426. Finish.
  5427. Executes statements until it has finished the current subroutine.
  5428. .Ip "c" 12 4
  5429. Continue.
  5430. Executes until the next breakpoint is reached.
  5431. .Ip "c line" 12 4
  5432. Continue to the specified line.
  5433. Inserts a one-time-only breakpoint at the specified line.
  5434. .Ip "<CR>" 12 4
  5435. Repeat last n or s.
  5436. .Ip "l min+incr" 12 4
  5437. List incr+1 lines starting at min.
  5438. If min is omitted, starts where last listing left off.
  5439. If incr is omitted, previous value of incr is used.
  5440. .Ip "l min-max" 12 4
  5441. List lines in the indicated range.
  5442. .Ip "l line" 12 4
  5443. List just the indicated line.
  5444. .Ip "l" 12 4
  5445. List next window.
  5446. .Ip "-" 12 4
  5447. List previous window.
  5448. .Ip "w line" 12 4
  5449. List window around line.
  5450. .Ip "l subname" 12 4
  5451. List subroutine.
  5452. If it's a long subroutine it just lists the beginning.
  5453. Use \*(L"l\*(R" to list more.
  5454. .Ip "/pattern/" 12 4
  5455. Regular expression search forward for pattern; the final / is optional.
  5456. .Ip "?pattern?" 12 4
  5457. Regular expression search backward for pattern; the final ? is optional.
  5458. .Ip "L" 12 4
  5459. List lines that have breakpoints or actions.
  5460. .Ip "S" 12 4
  5461. Lists the names of all subroutines.
  5462. .Ip "t" 12 4
  5463. Toggle trace mode on or off.
  5464. .Ip "b line condition" 12 4
  5465. Set a breakpoint.
  5466. If line is omitted, sets a breakpoint on the 
  5467. line that is about to be executed.
  5468. If a condition is specified, it is evaluated each time the statement is
  5469. reached and a breakpoint is taken only if the condition is true.
  5470. Breakpoints may only be set on lines that begin an executable statement.
  5471. .Ip "b subname condition" 12 4
  5472. Set breakpoint at first executable line of subroutine.
  5473. .Ip "d line" 12 4
  5474. Delete breakpoint.
  5475. If line is omitted, deletes the breakpoint on the 
  5476. line that is about to be executed.
  5477. .Ip "D" 12 4
  5478. Delete all breakpoints.
  5479. .Ip "a line command" 12 4
  5480. Set an action for line.
  5481. A multi-line command may be entered by backslashing the newlines.
  5482. .Ip "A" 12 4
  5483. Delete all line actions.
  5484. .Ip "< command" 12 4
  5485. Set an action to happen before every debugger prompt.
  5486. A multi-line command may be entered by backslashing the newlines.
  5487. .Ip "> command" 12 4
  5488. Set an action to happen after the prompt when you've just given a command
  5489. to return to executing the script.
  5490. A multi-line command may be entered by backslashing the newlines.
  5491. .Ip "V package" 12 4
  5492. List all variables in package.
  5493. Default is main package.
  5494. .Ip "! number" 12 4
  5495. Redo a debugging command.
  5496. If number is omitted, redoes the previous command.
  5497. .Ip "! -number" 12 4
  5498. Redo the command that was that many commands ago.
  5499. .Ip "H -number" 12 4
  5500. Display last n commands.
  5501. Only commands longer than one character are listed.
  5502. If number is omitted, lists them all.
  5503. .Ip "q or ^D" 12 4
  5504. Quit.
  5505. .Ip "command" 12 4
  5506. Execute command as a perl statement.
  5507. A missing semicolon will be supplied.
  5508. .Ip "p expr" 12 4
  5509. Same as \*(L"print DB'OUT expr\*(R".
  5510. The DB'OUT filehandle is opened to /dev/tty, regardless of where STDOUT
  5511. may be redirected to.
  5512. .PP
  5513. If you want to modify the debugger, copy perldb.pl from the perl library
  5514. to your current directory and modify it as necessary.
  5515. (You'll also have to put -I. on your command line.)
  5516. You can do some customization by setting up a .perldb file which contains
  5517. initialization code.
  5518. For instance, you could make aliases like these:
  5519. .nf
  5520.  
  5521.     $DB'alias{'len'} = 's/^len(.*)/p length($1)/';
  5522.     $DB'alias{'stop'} = 's/^stop (at|in)/b/';
  5523.     $DB'alias{'.'} =
  5524.       's/^\e./p "\e$DB\e'sub(\e$DB\e'line):\et",\e$DB\e'line[\e$DB\e'line]/';
  5525.  
  5526. .fi
  5527. .Sh "Setuid Scripts"
  5528. .I Perl
  5529. is designed to make it easy to write secure setuid and setgid scripts.
  5530. Unlike shells, which are based on multiple substitution passes on each line
  5531. of the script,
  5532. .I perl
  5533. uses a more conventional evaluation scheme with fewer hidden \*(L"gotchas\*(R".
  5534. Additionally, since the language has more built-in functionality, it
  5535. has to rely less upon external (and possibly untrustworthy) programs to
  5536. accomplish its purposes.
  5537. .PP
  5538. In an unpatched 4.2 or 4.3bsd kernel, setuid scripts are intrinsically
  5539. insecure, but this kernel feature can be disabled.
  5540. If it is,
  5541. .I perl
  5542. can emulate the setuid and setgid mechanism when it notices the otherwise
  5543. useless setuid/gid bits on perl scripts.
  5544. If the kernel feature isn't disabled,
  5545. .I perl
  5546. will complain loudly that your setuid script is insecure.
  5547. You'll need to either disable the kernel setuid script feature, or put
  5548. a C wrapper around the script.
  5549. .PP
  5550. When perl is executing a setuid script, it takes special precautions to
  5551. prevent you from falling into any obvious traps.
  5552. (In some ways, a perl script is more secure than the corresponding
  5553. C program.)
  5554. Any command line argument, environment variable, or input is marked as
  5555. \*(L"tainted\*(R", and may not be used, directly or indirectly, in any
  5556. command that invokes a subshell, or in any command that modifies files,
  5557. directories or processes.
  5558. Any variable that is set within an expression that has previously referenced
  5559. a tainted value also becomes tainted (even if it is logically impossible
  5560. for the tainted value to influence the variable).
  5561. For example:
  5562. .nf
  5563.  
  5564. .ne 5
  5565.     $foo = shift;            # $foo is tainted
  5566.     $bar = $foo,\'bar\';        # $bar is also tainted
  5567.     $xxx = <>;            # Tainted
  5568.     $path = $ENV{\'PATH\'};    # Tainted, but see below
  5569.     $abc = \'abc\';            # Not tainted
  5570.  
  5571. .ne 4
  5572.     system "echo $foo";        # Insecure
  5573.     system "/bin/echo", $foo;    # Secure (doesn't use sh)
  5574.     system "echo $bar";        # Insecure
  5575.     system "echo $abc";        # Insecure until PATH set
  5576.  
  5577. .ne 5
  5578.     $ENV{\'PATH\'} = \'/bin:/usr/bin\';
  5579.     $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
  5580.  
  5581.     $path = $ENV{\'PATH\'};    # Not tainted
  5582.     system "echo $abc";        # Is secure now!
  5583.  
  5584. .ne 5
  5585.     open(FOO,"$foo");        # OK
  5586.     open(FOO,">$foo");         # Not OK
  5587.  
  5588.     open(FOO,"echo $foo|");    # Not OK, but...
  5589.     open(FOO,"-|") || exec \'echo\', $foo;    # OK
  5590.  
  5591.     $zzz = `echo $foo`;        # Insecure, zzz tainted
  5592.  
  5593.     unlink $abc,$foo;        # Insecure
  5594.     umask $foo;            # Insecure
  5595.  
  5596. .ne 3
  5597.     exec "echo $foo";        # Insecure
  5598.     exec "echo", $foo;        # Secure (doesn't use sh)
  5599.     exec "sh", \'-c\', $foo;    # Considered secure, alas
  5600.  
  5601. .fi
  5602. The taintedness is associated with each scalar value, so some elements
  5603. of an array can be tainted, and others not.
  5604. .PP
  5605. If you try to do something insecure, you will get a fatal error saying 
  5606. something like \*(L"Insecure dependency\*(R" or \*(L"Insecure PATH\*(R".
  5607. Note that you can still write an insecure system call or exec,
  5608. but only by explicitly doing something like the last example above.
  5609. You can also bypass the tainting mechanism by referencing
  5610. subpatterns\*(--\c
  5611. .I perl
  5612. presumes that if you reference a substring using $1, $2, etc, you knew
  5613. what you were doing when you wrote the pattern:
  5614. .nf
  5615.  
  5616.     $ARGV[0] =~ /^\-P(\ew+)$/;
  5617.     $printer = $1;        # Not tainted
  5618.  
  5619. .fi
  5620. This is fairly secure since \ew+ doesn't match shell metacharacters.
  5621. Use of .+ would have been insecure, but
  5622. .I perl
  5623. doesn't check for that, so you must be careful with your patterns.
  5624. This is the ONLY mechanism for untainting user supplied filenames if you
  5625. want to do file operations on them (unless you make $> equal to $<).
  5626. .PP
  5627. It's also possible to get into trouble with other operations that don't care
  5628. whether they use tainted values.
  5629. Make judicious use of the file tests in dealing with any user-supplied
  5630. filenames.
  5631. When possible, do opens and such after setting $> = $<.
  5632. .I Perl
  5633. doesn't prevent you from opening tainted filenames for reading, so be
  5634. careful what you print out.
  5635. The tainting mechanism is intended to prevent stupid mistakes, not to remove
  5636. the need for thought.
  5637. .SH ENVIRONMENT
  5638. .I Perl
  5639. uses PATH in executing subprocesses, and in finding the script if \-S
  5640. is used.
  5641. HOME or LOGDIR are used if chdir has no argument.
  5642. .PP
  5643. Apart from these,
  5644. .I perl
  5645. uses no environment variables, except to make them available
  5646. to the script being executed, and to child processes.
  5647. However, scripts running setuid would do well to execute the following lines
  5648. before doing anything else, just to keep people honest:
  5649. .nf
  5650.  
  5651. .ne 3
  5652.     $ENV{\'PATH\'} = \'/bin:/usr/bin\';    # or whatever you need
  5653.     $ENV{\'SHELL\'} = \'/bin/sh\' if $ENV{\'SHELL\'} ne \'\';
  5654.     $ENV{\'IFS\'} = \'\' if $ENV{\'IFS\'} ne \'\';
  5655.  
  5656. .fi
  5657. .SH AUTHOR
  5658. Larry Wall <lwall@netlabs.com>
  5659. .br
  5660. MS-DOS port by Diomidis Spinellis <dds@cc.ic.ac.uk>
  5661. .SH FILES
  5662. /tmp/perl\-eXXXXXX    temporary file for
  5663. .B \-e
  5664. commands.
  5665. .SH SEE ALSO
  5666. a2p    awk to perl translator
  5667. .br
  5668. s2p    sed to perl translator
  5669. .SH DIAGNOSTICS
  5670. Compilation errors will tell you the line number of the error, with an
  5671. indication of the next token or token type that was to be examined.
  5672. (In the case of a script passed to
  5673. .I perl
  5674. via
  5675. .B \-e
  5676. switches, each
  5677. .B \-e
  5678. is counted as one line.)
  5679. .PP
  5680. Setuid scripts have additional constraints that can produce error messages
  5681. such as \*(L"Insecure dependency\*(R".
  5682. See the section on setuid scripts.
  5683. .SH TRAPS
  5684. Accustomed
  5685. .IR awk
  5686. users should take special note of the following:
  5687. .Ip * 4 2
  5688. Semicolons are required after all simple statements in
  5689. .IR perl .
  5690. Newline
  5691. is not a statement delimiter.
  5692. .Ip * 4 2
  5693. Curly brackets are required on ifs and whiles.
  5694. .Ip * 4 2
  5695. Variables begin with $ or @ in
  5696. .IR perl .
  5697. .Ip * 4 2
  5698. Arrays index from 0 unless you set $[.
  5699. Likewise string positions in substr() and index().
  5700. .Ip * 4 2
  5701. You have to decide whether your array has numeric or string indices.
  5702. .Ip * 4 2
  5703. Associative array values do not spring into existence upon mere reference.
  5704. .Ip * 4 2
  5705. You have to decide whether you want to use string or numeric comparisons.
  5706. .Ip * 4 2
  5707. Reading an input line does not split it for you.  You get to split it yourself
  5708. to an array.
  5709. And the
  5710. .I split
  5711. operator has different arguments.
  5712. .Ip * 4 2
  5713. The current input line is normally in $_, not $0.
  5714. It generally does not have the newline stripped.
  5715. ($0 is the name of the program executed.)
  5716. .Ip * 4 2
  5717. $<digit> does not refer to fields\*(--it refers to substrings matched by the last
  5718. match pattern.
  5719. .Ip * 4 2
  5720. The
  5721. .I print
  5722. statement does not add field and record separators unless you set
  5723. $, and $\e.
  5724. .Ip * 4 2
  5725. You must open your files before you print to them.
  5726. .Ip * 4 2
  5727. The range operator is \*(L".\|.\*(R", not comma.
  5728. (The comma operator works as in C.)
  5729. .Ip * 4 2
  5730. The match operator is \*(L"=~\*(R", not \*(L"~\*(R".
  5731. (\*(L"~\*(R" is the one's complement operator, as in C.)
  5732. .Ip * 4 2
  5733. The exponentiation operator is \*(L"**\*(R", not \*(L"^\*(R".
  5734. (\*(L"^\*(R" is the XOR operator, as in C.)
  5735. .Ip * 4 2
  5736. The concatenation operator is \*(L".\*(R", not the null string.
  5737. (Using the null string would render \*(L"/pat/ /pat/\*(R" unparsable,
  5738. since the third slash would be interpreted as a division operator\*(--the
  5739. tokener is in fact slightly context sensitive for operators like /, ?, and <.
  5740. And in fact, . itself can be the beginning of a number.)
  5741. .Ip * 4 2
  5742. .IR Next ,
  5743. .I exit
  5744. and
  5745. .I continue
  5746. work differently.
  5747. .Ip * 4 2
  5748. The following variables work differently
  5749. .nf
  5750.  
  5751.       Awk    \h'|2.5i'Perl
  5752.       ARGC    \h'|2.5i'$#ARGV
  5753.       ARGV[0]    \h'|2.5i'$0
  5754.       FILENAME\h'|2.5i'$ARGV
  5755.       FNR    \h'|2.5i'$. \- something
  5756.       FS    \h'|2.5i'(whatever you like)
  5757.       NF    \h'|2.5i'$#Fld, or some such
  5758.       NR    \h'|2.5i'$.
  5759.       OFMT    \h'|2.5i'$#
  5760.       OFS    \h'|2.5i'$,
  5761.       ORS    \h'|2.5i'$\e
  5762.       RLENGTH    \h'|2.5i'length($&)
  5763.       RS    \h'|2.5i'$/
  5764.       RSTART    \h'|2.5i'length($\`)
  5765.       SUBSEP    \h'|2.5i'$;
  5766.  
  5767. .fi
  5768. .Ip * 4 2
  5769. When in doubt, run the
  5770. .I awk
  5771. construct through a2p and see what it gives you.
  5772. .PP
  5773. Cerebral C programmers should take note of the following:
  5774. .Ip * 4 2
  5775. Curly brackets are required on ifs and whiles.
  5776. .Ip * 4 2
  5777. You should use \*(L"elsif\*(R" rather than \*(L"else if\*(R"
  5778. .Ip * 4 2
  5779. .I Break
  5780. and
  5781. .I continue
  5782. become
  5783. .I last
  5784. and
  5785. .IR next ,
  5786. respectively.
  5787. .Ip * 4 2
  5788. There's no switch statement.
  5789. .Ip * 4 2
  5790. Variables begin with $ or @ in
  5791. .IR perl .
  5792. .Ip * 4 2
  5793. Printf does not implement *.
  5794. .Ip * 4 2
  5795. Comments begin with #, not /*.
  5796. .Ip * 4 2
  5797. You can't take the address of anything.
  5798. .Ip * 4 2
  5799. ARGV must be capitalized.
  5800. .Ip * 4 2
  5801. The \*(L"system\*(R" calls link, unlink, rename, etc. return nonzero for success, not 0.
  5802. .Ip * 4 2
  5803. Signal handlers deal with signal names, not numbers.
  5804. .PP
  5805. Seasoned
  5806. .I sed
  5807. programmers should take note of the following:
  5808. .Ip * 4 2
  5809. Backreferences in substitutions use $ rather than \e.
  5810. .Ip * 4 2
  5811. The pattern matching metacharacters (, ), and | do not have backslashes in front.
  5812. .Ip * 4 2
  5813. The range operator is .\|. rather than comma.
  5814. .PP
  5815. Sharp shell programmers should take note of the following:
  5816. .Ip * 4 2
  5817. The backtick operator does variable interpretation without regard to the
  5818. presence of single quotes in the command.
  5819. .Ip * 4 2
  5820. The backtick operator does no translation of the return value, unlike csh.
  5821. .Ip * 4 2
  5822. Shells (especially csh) do several levels of substitution on each command line.
  5823. .I Perl
  5824. does substitution only in certain constructs such as double quotes,
  5825. backticks, angle brackets and search patterns.
  5826. .Ip * 4 2
  5827. Shells interpret scripts a little bit at a time.
  5828. .I Perl
  5829. compiles the whole program before executing it.
  5830. .Ip * 4 2
  5831. The arguments are available via @ARGV, not $1, $2, etc.
  5832. .Ip * 4 2
  5833. The environment is not automatically made available as variables.
  5834. .SH ERRATA\0AND\0ADDENDA
  5835. The Perl book,
  5836. .I Programming\0Perl ,
  5837. has the following omissions and goofs.
  5838. .PP
  5839. On page 5, the examples which read
  5840. .nf
  5841.  
  5842.     eval "/usr/bin/perl
  5843.  
  5844. should read
  5845.  
  5846.     eval "exec /usr/bin/perl
  5847.  
  5848. .fi
  5849. .PP
  5850. On page 195, the equivalent to the System V sum program only works for
  5851. very small files.  To do larger files, use
  5852. .nf
  5853.  
  5854.     undef $/;
  5855.     $checksum = unpack("%32C*",<>) % 32767;
  5856.  
  5857. .fi
  5858. .PP
  5859. The descriptions of alarm and sleep refer to signal SIGALARM.  These
  5860. should refer to SIGALRM.
  5861. .PP
  5862. The
  5863. .B \-0
  5864. switch to set the initial value of $/ was added to Perl after the book
  5865. went to press.
  5866. .PP
  5867. The
  5868. .B \-l
  5869. switch now does automatic line ending processing.
  5870. .PP
  5871. The qx// construct is now a synonym for backticks.
  5872. .PP
  5873. $0 may now be assigned to set the argument displayed by
  5874. .I ps (1).
  5875. .PP
  5876. The new @###.## format was omitted accidentally from the description
  5877. on formats.
  5878. .PP
  5879. It wasn't known at press time that s///ee caused multiple evaluations of
  5880. the replacement expression.  This is to be construed as a feature.
  5881. .PP
  5882. (LIST) x $count now does array replication.
  5883. .PP
  5884. There is now no limit on the number of parentheses in a regular expression.
  5885. .PP
  5886. In double-quote context, more escapes are supported: \ee, \ea, \ex1b, \ec[,
  5887. \el, \eL, \eu, \eU, \eE.  The latter five control up/lower case translation.
  5888. .PP
  5889. The
  5890. .B $/
  5891. variable may now be set to a multi-character delimiter.
  5892. .PP
  5893. There is now a g modifier on ordinary pattern matching that causes it
  5894. to iterate through a string finding multiple matches.
  5895. .PP
  5896. All of the $^X variables are new except for $^T.
  5897. .PP
  5898. The default top-of-form format for FILEHANDLE is now FILEHANDLE_TOP rather
  5899. than top.
  5900. .PP
  5901. The eval {} and sort {} constructs were added in version 4.018.
  5902. .PP
  5903. The v and V (little-endian) template options for pack and unpack were
  5904. added in 4.019.
  5905. .SH BUGS
  5906. .PP
  5907. .I Perl
  5908. is at the mercy of your machine's definitions of various operations
  5909. such as type casting, atof() and sprintf().
  5910. .PP
  5911. If your stdio requires an seek or eof between reads and writes on a particular
  5912. stream, so does
  5913. .IR perl .
  5914. (This doesn't apply to sysread() and syswrite().)
  5915. .PP
  5916. While none of the built-in data types have any arbitrary size limits (apart
  5917. from memory size), there are still a few arbitrary limits:
  5918. a given identifier may not be longer than 255 characters,
  5919. and no component of your PATH may be longer than 255 if you use \-S.
  5920. .PP
  5921. .I Perl
  5922. actually stands for Pathologically Eclectic Rubbish Lister, but don't tell
  5923. anyone I said that.
  5924. .rn }` ''
  5925.